问题
I use OleDB to read an Excel file. One of the columns has a "Common" format and contains both strings with letters and values consisting of numbers only. String values are retrieved without problem, but pure numerical values are retrieved as DBNull
.
How to solve?
I use the following connection string to open Excel 2003 file (xls):
"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\\file.xls;
Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\""
回答1:
I found some documentation on Microsoft's website that applies to your scenario. They recommend converting all the numerics to strings.
http://support.microsoft.com/kb/257819
As stated previously, ADO must guess at the data type for each column in your Excel worksheet or range. (This is not affected by Excel cell formatting settings.) A serious problem can arise if you have numeric values mixed with text values in the same column. Both the Jet and the ODBC Provider return the data of the majority type, but return NULL (empty) values for the minority data type. If the two types are equally mixed in the column, the provider chooses numeric over text.
For example:
* In your eight (8) scanned rows, if the column contains five (5) numeric values and three (3) text values, the provider returns five (5) numbers and three (3) null values.
* In your eight (8) scanned rows, if the column contains three (3) numeric values and five (5) text values, the provider returns three (3) null values and five (5) text values.
* In your eight (8) scanned rows, if the column contains four (4) numeric values and four (4) text values, the provider returns four (4) numbers and four (4) null values.
回答2:
I have the same problem but with string values. Numeric values are returned but string values are returned as NULL. I want to load numeric values as string values. The column can contain digits and non-numeric codes (example: 100344567 and PRD001X01).
The Excel driver considers that the column is of type numeric because the values in the first 8 rows are of type numeric.
Even if I define the cells as Text (Format Cell) it does not work.
To force the driver to "see" the column as string I have simply put a quote in front of the numeric value ('100344567). This turns the numeric value into a string.
This value of 8 rows is defined in the Registry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel\ -->TypeGuessRows=8.
I hope it will help.
来源:https://stackoverflow.com/questions/3206915/dbnull-in-non-empty-cell-when-reading-excel-file-through-oledb