从内存流中检索数据表。
我有一个由列名数组格式化的数据表,即
DataTable ThisTable = new DataTable();
for (int i = 0; i <= col.GetUpperBound(0); i++)
{
try
{
ThisTable.Columns.Add(new DataColumn(col[i].ToString(), typeof(string)));
}
catch (Exception e)
{
MessageBox.Show("Uploader Error"+e.ToString());
return null;
}
}
我然后使用 BinaryFormatter 对象来序列化/反序列化内存流,以便我可以将数据从流读取到表中。本质上,用户将上传一个 Excel 工作表,该工作表将被读入数据库。尽管我意识到这是可能的,但我不想将工作表写入磁盘然后将其读入。
但是,当我从 Deserialize()
调用检索数据表时,我没有收到错误,但得到了一个空的数据集。
Mem 将是我的内存流对象。
BinaryFormatter bformat = new BinaryFormatter();
bformat.Serialize(Mem, ThisTable);
Mem.Seek(0, SeekOrigin.Begin);
byte[] bt = Mem.ToArray();
Stream s = new MemoryStream(bt);
Mem.Position = 0;
s.Position = 0;
ThisTable = (DataTable)bformat.Deserialize(Mem);
DS.Tables.Add(ThisTable);
return DS;
I have a data table that is formatted from an array of Column Names, I.e.
DataTable ThisTable = new DataTable();
for (int i = 0; i <= col.GetUpperBound(0); i++)
{
try
{
ThisTable.Columns.Add(new DataColumn(col[i].ToString(), typeof(string)));
}
catch (Exception e)
{
MessageBox.Show("Uploader Error"+e.ToString());
return null;
}
}
i then use a BinaryFormatter
object to Serialize/Deserialize a memory stream so that I can read the data from the stream into a table. Essentially users will be uploading an excel sheet that will be read into a database. Although I realize that it is possible, I DO NOT want to write the sheet to disk then read it in.
However when I go to retrieve the datatable from the Deserialize()
call, I dont get an error, however I get an empty DataSet.
Mem would be my memory stream object.
BinaryFormatter bformat = new BinaryFormatter();
bformat.Serialize(Mem, ThisTable);
Mem.Seek(0, SeekOrigin.Begin);
byte[] bt = Mem.ToArray();
Stream s = new MemoryStream(bt);
Mem.Position = 0;
s.Position = 0;
ThisTable = (DataTable)bformat.Deserialize(Mem);
DS.Tables.Add(ThisTable);
return DS;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用 OpenXml SDK 将 Excel 文件读入数据表。
以 M_R_H 的答案为例:
来自 Excel to DataTable in C# with Open XML
您还可以在此处查看 amurra 的答案,了解另一个示例:
读取 Excel Open XML 会忽略空白单元格
I would suggest using the OpenXml SDK to read the Excel file into the DataTable.
Take a look at the answer from M_R_H for an example:
From Excel to DataTable in C# with Open XML
You can also look at the answer from amurra here for another example:
reading Excel Open XML is ignoring blank cells
除非您发布的示例代码中有错误,否则您不会使用任何数据填充 DataTable,而只是创建列。您可以通过 DataTable.Rows.Add() 向 DataTable 添加行:
Unless there is an error in the sample code you posted, you aren't populating the DataTable with any data, you are just creating columns. You can add rows to the DataTable via
DataTable.Rows.Add()
: