你也許我重定向到這一個環節,但我會是第一個告訴你們:我用這個了很多次,我真不這次不知道什麼問題。asp.net - 閱讀Excel工作表的名稱不返回數據表
我的情況是:我需要將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;
}
}
它拋出一個異常,稱該數據表的行數爲0。我也用DataTable dt = oleConn.GetSchema("Tables")
和
DataTable dt = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new Object[] {null, null, null, "TABLE"});
,但他們都返回相同。
可能是什麼問題?它可能是Excel文件嗎?但我試過其他Excel文件,都失敗了。
你可以發佈'DataTable dt'的調試可視化器嗎? – Hassan 2014-09-02 04:34:19