Question

I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?

Was it helpful?

Solution

I believe you have to set the option in your connect string to force textual import rather than auto-detecting it.

Provider=Microsoft.ACE.OLEDB.12.0;
    Data Source=c:\path\to\myfile.xlsx;
    Extended Properties=\"Excel 12.0 Xml;IMEX=1\";

Your milage may vary depending on the version you have installed. The IMEX=1 extended property tells Excel to treat intermixed data as text.

OTHER TIPS

Prefix with '

Prefixing the contents of the cell with ' forces Excel to see it as text instead of a number. The ' won't be displayed in Excel.

There is a registry hack that can force Excel to read more than the first 8 rows when reading a column to determine the type:

Change

HKLM\Software\Microsoft\Jet\4.0\Engines\Excel\TypeGuessRows 

To be 0 to read all rows, or another number to set it to that number of rows.

Not that this will have a slighht performance hit.

I think the way to do this would be to format the source excel file such that the column is formatted as Text instead of General. Select the entire column and right click and select format cells, select text from the list of options.

I think that would explicitly define that the column content is text and should be treated as such.

Let me know if that works.

Saving the file as a tab delimited text file has also worked well.

---old Unfortunately, we can't rely on the columns of the excel doc to stay in a particular format as the users will be pasting data into it regularly. I don't want the app to crash if we're relying on a certain datatype for a column.

prefixing with ' would work, is there a reasonable way to do that programatically once the data already exists in the excel doc?

Sending value 00022556 as '=" 00022556"' from Sql server is excellent way to handle leading zero problem

Add "\t" before your string. It'll make the string seem in a new tab.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top