0

I have an application, on which i export data from a datagrid to a csv file. I do this with the following steps:

  1. Create a file:

    var myFile = File.Create("test.csv"); myfile.Close();

  2. write the data to a string builder(data)

  3. write the data to the created file.

    File.WriteAllText(filepath, data);

This works fine. The resulting csv file is opened in excel. I have a column of numbers which may have preceeding zeros, when those data is exported to csv file the preceeding 0's are lost. Is it possible to format the column as text column so the zeros are not lost.

3
  • One thing you could try is saving as text file then renaming to .csv Commented Jun 4, 2015 at 23:40
  • 1
    Your code should not trim leading zeros. Are you by any chance opening the resulting .csv file in Excel? Excel tends to do this. Commented Jun 4, 2015 at 23:40
  • Yes, the resulting csv file is opened and used in Excel Commented Jun 4, 2015 at 23:41

1 Answer 1

2

View your file in notepad. The leading zeros are there, intact :-)

You need to tell Excel which format to use when you open the file. Change the file to .txt and use File -> Open in Excel and you should be presented with an import wizard. There you can explicitly tell Excel to treat your column as "text" which will prevent it from stripping leading zeroes.

More info here: http://www.howtogeek.com/howto/microsoft-office/how-to-import-a-csv-file-containing-a-column-with-a-leading-0-into-excel/

Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way to automatically do this in C#, the users would see this as extra work and would expect this to be done on its own.
Keep in mind that your file is not really the problem, Excel is :-) However, I believe that if you prefix the leading zeros with a single quote character, Excel will no longer strip the leading zeros.
Yes, I thought of that. But then again the users need to remove the quotes. I couldnt find any other solution and hence this post :)
No, that's the thing. Excel will not display the single quote :-) Try it!
I tried it and excel displays the numbers with quotes. I did data.Append("'").Append(000123).Append("'");
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.