[英]Excel to DataTable Error in c#
我有一个奇怪的问题,
当我尝试打开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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.