我嘗試使用OLEDB將Excel文件保存到C#上的DataTable中時出現問題。Oledb跳過Excel文件的第一列
該DataTable沒有我的Excel文件的第一列,但有一個額外的空列作爲最後一列。我不知道我做錯了什麼。如果我的Excel文件有這樣的事情:
ID,姓名,ADRESS
的數據表列如下:
名稱,ADRESS,F3(空)
這裏是我的功能:
public DataTable GetExcel(string[] files, string sheetName, string pathName)
{
for (int i = 0; i < files.Length; i++)
{
string strConn = string.Empty;
if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
FileInfo file = new FileInfo(files[i]);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection cnnxls = new OleDbConnection(strConn);
OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
oda.Fill(dataTable);
}
return dataTable;
}
謝謝!
自行製作欄目,比如'dataTable.Columns .Add(「Name」,typeof(string)'在調用'oda.Fill(dataTable)'之前' – Nino
它不起作用,我仍然有一個空的最後一列,它錯過了第一個,非常感謝你 –
Adapter如果你知道你的單元格的範圍,你可以像這樣查詢表單:'string.Format(「select * from [{0} $ A1:C200 ]「,sheetName)' – Nino