asp.net – 阅读Excel表名不返回数据表

你可能会把我redirect到这个链接,但是我会第一个告诉你们:我曾经使用过这么多次,我真的不知道这次是什么问题。

我的情况是:我需要将Excel数据导入到数据库中。 听起来很简单,对吧? 现在,首先我需要知道表单名称。 这是我的问题开始的地方。 我再说一遍,我已经多次使用过了,这次我不知道自己做错了什么:

我所说的“它”就是这样一段代码:

public string[] GetSheetNames(string excelPath) { try { string[] ar = null; if (Path.GetExtension(excelPath) == ".xls") { conString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""); } else if (Path.GetExtension(excelPath) == ".xlsx") { conString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";"); } using (oleConn = new OleDbConnection(conString)) { oleConn.Open(); if (oleConn.State == ConnectionState.Open) { //DataTable dt = oleConn.GetSchema("Tables"); //DataTable dt = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] {null, null, null, "TABLE"}); DataTable dt = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dt == null) { return null; } ar = new string[dt.Rows.Count]; int t = 0; foreach(DataRow dr in dt.Rows){ ar[t] = dr["TABLE_NAME"].ToString(); t++; } } return ar; } } catch (Exception) { throw; } } 

它抛出一个exception,说DataTable的行数是0.我也用DataTable dt = oleConn.GetSchema("Tables")

 DataTable dt = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] {null, null, null, "TABLE"}); 

但他们都回来了。

可能是什么问题呢? 可以是Excel文件吗? 但我已经尝试了其他的Excel文件,他们都失败了。

试试这个代码:

  OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0 xml;HDR=YES;'"); connection.Open(); DataTable Sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); foreach (DataRow dr in Sheets.Rows) { string sht = dr[2].ToString().Replace("'", ""); OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + sht + "]", connection); } 

我不知道你是否仍然需要select,但这只是发生在我身上,我得到了一个解决scheme。

我的问题是文件本身,当复制到本地文件夹我没有添加扩展,所以当连接打开它创build一个空的文件没有工作表(这是没有表读取)

如果您要将文件移动到本地文件夹,请查看文件并查看它是否已损坏,并在复制后确实需要读取内容。

 private DataSet GetExcelWorkSheet(string pathName, string fileName, int workSheetNumber) { OleDbConnection ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + @"\" + fileName + ";Extended Properties=Excel 8.0;"); OleDbCommand ExcelCommand = new OleDbCommand(); ExcelCommand.Connection = ExcelConnection; OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand); ExcelConnection.Open(); DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); string SpreadSheetName = "[" + ExcelSheets.Rows[workSheetNumber]["TABLE_NAME"].ToString() + "]"; DataSet ExcelDataSet = new DataSet(); ExcelCommand.CommandText = @"SELECT * FROM " + SpreadSheetName; ExcelAdapter.Fill(ExcelDataSet); ExcelConnection.Close(); return ExcelDataSet; }