c#中的Excel到DataTable错误
本文关键字:DataTable 错误 Excel 中的 | 更新日期: 2023-09-27 18:28:18
我有一个奇怪的问题,
当我尝试打开excel数据并将其加载到DataTable时,
excel表中的某些数据加载,但某些数据未加载,
问题出在哪里,
你能帮我吗?
我添加了GetExcelData函数,
请查看此代码,
请告诉我出了什么问题。
GROUP CLASS TYPE C1 C2 C3 C4 C4 C5
M1 10 A D B D A A D
M1 10 B C D E E D D
M2 11 A D D D D D E
M2 11 B C D E D E A
我把样品单放在上面
它只复制GROUP、CLASS和TYPE列中的数据
但奇怪的是,在一些excel文件中没有出现这种错误,
我没有找到答案,决定在这里问。
public DataTable GetExcelData(string fileName, string sheetName)
{
string sql = "";
OleDbConnection conn = new OleDbConnection();
OleDbCommand command;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
command = conn.CreateCommand();
string excel_file = fileName;
string excel_type = System.IO.Path.GetExtension(excel_file);
string connstr = "";
if(excel_type=="XLSX")
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0";
else
connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +fileName + ";Extended Properties='Excel 12.0;IMEX=1; HDR=YES'";
conn.ConnectionString = connstr;
sql = "SELECT * FROM [" + sheetName + "$]";
command.CommandText = sql;
adapter.SelectCommand = command;
adapter.Fill(dt);
return dt;
}
因为您的第一个连接字符串
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0";
没有IMEX=1,它将无法导入混合类型的列,这种情况有时只会发生,因为您的if子句。与HDR相同,在1种情况下HDR丢失。如果条件应该是,中的连接字符串
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0;HDR=Yes;IMEX=1";