我将一个 excel 文件导入 DataTable,然后从每个后续 DataRow 中获取我需要的信息,然后将这些信息插入到列表中。我有一个方法,当我需要将 Excel(.xlsx 或 .xls)文件导入 DataTable 时调用它,我在程序中的 6 或 7 个其他地方使用它,所以我很确定没有任何那里的错误。
我的问题是,当我在这个特定的 DataTable 上访问 DataRow 时,前几个字段包含值,但其他所有内容都为空。如果我在 Locals 窗口中查看它,我可以看到 DataRow 看起来像这样:
[0] {"Some string value"}
[1] {}
[2] {}
[3] {}
什么时候应该是这样的:
[0] {"Some string value"}
[1] {"Another string value"}
[2] {"Foo"}
[3] {"Bar"}
这是处理导入的方法:
public List<DataTable> ImportExcel(string FileName)
{
List<DataTable> _dataTables = new List<DataTable>();
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
//Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0";
}
//Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0";
}
DataTable dataTable = null;
var count = 0;
using (OleDbConnection oleDbConnection =
new OleDbConnection(string.Format(_ConnectionString, FileName)))
{
oleDbConnection.Open();
//Getting the meta data information.
//This DataTable will return the details of Sheets in the Excel File.
DataTable dbSchema = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null);
foreach (DataRow item in dbSchema.Rows)
{
//reading data from excel to Data Table
using (OleDbCommand oleDbCommand = new OleDbCommand())
{
oleDbCommand.Connection = oleDbConnection;
oleDbCommand.CommandText = string.Format("SELECT * FROM [{0}]",
item["TABLE_NAME"].ToString());
using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter())
{
if (count < 3)
{
oleDbDataAdapter.SelectCommand = oleDbCommand;
dataTable = new DataTable(item["TABLE_NAME"].ToString());
oleDbDataAdapter.Fill(dataTable);
_dataTables.Add(dataTable);
count++;
}
}
}
}
}
return _dataTables;
}
有什么想法吗?