将Excel文件读入DataTable将返回DataRows中的空字段

我将一个excel文件导入到一个DataTable中,然后从每个后续的DataRow获取所需的信息,然后将其插入到列表中。 我有一个方法,当我需要将一个Excel(.xlsx或.xls)文件导入到一个DataTable中时,我会调用它,并且在我的程序中使用它6或7个其他位置,所以我很确定没有任何错误在那里。

我的问题是,当我访问一个DataRow,在这个特定的DataTable,前几个字段包含值,但其他一切都是空的。 如果我在“本地”窗口中查看它,则可以看到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; } 

有什么想法吗?

您可能需要在连接string中将“ ;IMEX=1 ”添加到“扩展属性”。 但最终,用OleDb读取excel文件最好不过了。 你应该使用一个第三方库,像这样处理它们:

用于XLS的NPOI https://code.google.com/p/npoi/

EPPlus for XLSX http://epplus.codeplex.com/

原来的错误是用excel文件。 显然excel文件有一个名为Shared Strings的隐藏表。 那是因为这张桌子我找不到我正在寻找的价值。