【发布时间】:2017-05-02 08:12:28
【问题描述】:
当我尝试使用 OLEDB 将 Excel 文件保存到 C# 上的 DataTable 时遇到问题。
DataTable 没有我的 Excel 文件的第一列,但有一个额外的空列作为最后一列。我不知道我做错了什么。如果我的 Excel 文件有这样的内容:
身份证、姓名、地址
DataTable 列是:
姓名、地址、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;
}
谢谢!
【问题讨论】:
-
在调用
oda.Fill(dataTable)之前自己创建列,例如dataTable.Columns.Add("Name", typeof(string) -
它不起作用,我还有一个空的最后一列,它错过了第一列。非常感谢。
-
适配器从查询中猜测表列,有时会发生类似的事情。你知道你的细胞的范围吗?如果你这样做,你可以像这样查询表:
string.Format("select * from [{0}$A1:C200]", sheetName) -
为什么不只选择整个工作表?
-
@Nino 我永远不会知道范围,无论如何我都试过了,现在没有创建一个空列但仍然错过了第一个列,谢谢。