我正在使用 OLEDB 数据提供程序 读取 Excel 文件,但问题在于 Excel 表格中某些列具有无效值,例如,某些单元格中出现了字符串而不是数字。
对于上面的截图,当我读取“John”这个值时,会得到一个空字符串。
那么有没有办法读取这个无效值?
非常感谢任何帮助。
以下是读取 Excel 文件的代码:
private DataTable ReadExcelFile(string sheetName, string path)
{
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = path;
string fileExtension = Path.GetExtension(Import_FileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [" + sheetName + "$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
return dt;
}
}
}
}
HDR=YES
之后的连接字符串中加入;IMEX=1
,可以实现同样的功能。 - Doug Glancy