使用OLEDB数据提供程序读取excel文件

我正在使用OLEDB数据提供程序来读取excel文件,但问题是,在Excel表中,一些cloumn有一个无效的值例如,而不是数字string在那里,当我读取这个无效的值,我得到一个空string,而不是实际值。

在这里输入图像说明

为上面的截图,当我读取值约翰获得空string。

那么有什么方法可以读取这个无效值吗?

任何帮助将不胜感激。

代码是读取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; } } } } 

您需要将TypeGuessRowsregistry项的值设置为0,这样驱动程序将基于所有列值而不是前8(默认值)设置数据types。

键的位置不同,从版本到版本的驱动程序,你可以很容易地谷歌它基于您的具体版本。 例如对于Access连接引擎2007它将是

 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\12.0\Access Connectivity Engine\Engines\Excel 

顺便说一句,你不需要Jet来读取XLS文件,ACE也完全能够做到这一点。

这对我有效

  using (OleDbConnection conn = new OleDbConnection()) { DataTable dt = new DataTable(); conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;MAXSCANROWS=0'"; 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; } } } 

MAXSCANROWS = 0覆盖registry默认值,并在确定types之前扫描所有行。 IMEX = 1仍然需要包括在内。

例如,给定这个表格:

 Header | Header ------ | ------ Cell1 | 2456354 Cell2 | 2456354 Cell3 | 2456354 Cell4 | 2456354 Cell5 | 2456354 Cell6 | 2456354 Cell7 | 2456354 Cell8 | 2456354 Cell9 | A5341 

以下连接string将丢失A5341

 "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'" "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;MAXSCANROWS=0'" 

但是它在两者兼有的情况下都有效。