开发者

excel to DataTable to csv Zip Codes w/ Hyphens not showing using C# OLEDB

开发者 https://www.devze.com 2023-02-07 13:58 出处:网络
I have an excel s开发者_高级运维preadsheet which contains addresses.I\'m reading the data from the spreadsheet using OLEDB and storing it into a DataTable.I then loop through the DataTable and create

I have an excel s开发者_高级运维preadsheet which contains addresses. I'm reading the data from the spreadsheet using OLEDB and storing it into a DataTable. I then loop through the DataTable and create my output, which is written to a .csv file. I'm doing all of this in C#.

Here's the problem: When I open the .csv file, any zip codes that were hyphenated have been replaced with 0's.

12345-1234 --> 0

So I want to correct this behavior so that the zip code appears as it should. If i have to chop off the digits after the hyphen, that would be fine. How can I ensure the zip code gets transferred?

Also, is there something I can do in code to maintain the leading 0's in a zip code? Zip codes like this:

01234 --> 1234

Is there something I can do in code to keep the leading 0?


The problem is that CSV files have to be interpreted by Excel and its assuming that something that looks numeric should be treated according to the default numeric rules. The fixes, unfortunately, don't work for all possible cases. You can do one of the following options:

  1. Keep the CSV file as is and use the Data Import wizard in Excel
  2. Write a leading tick ' to the field
  3. Write the field as an equation ="01234"

If you're just using Excel to look at the data then the second or third option might work. If you need to use the data in additional formulas then you might want to go the first route. If you're inspecting the data in Excel but you're going to use it elsewhere I'd recommend going the first route, too.


If the zip codes are formatted in the excel spreadsheet, you should read them in, store them in memory, and write them out all as strings. Do NOT convert them to integers.


I just tested your data and this method posted here worked.

i.e. the cell value kept its value "12345-1234", when put into DataSet. Also leading zeros are sent to the DataSet as well. (zip code of: 00601)

0

精彩评论

暂无评论...
验证码 换一张
取 消