0

In my project I generate a CSV file for the user to download. In one of the columns there are values that can start with 0. However when the user downloads the file and opens it the zeros disappear.

user1908466
  • 503
  • 1
  • 8
  • 17

3 Answers3

2

You need to 'define' your output as a string instead of a number.

I assume you now have something like:

field1,01245254,field3

Which results in:

field1 | 1245254 | field3

If you would format your csv as:

"field1","01245254","field3"

It would result in:

field1 | 01245254 | field3
Pieter De Schepper
  • 486
  • 1
  • 4
  • 10
1

The csv file will likely hold the value with the leading zeroes if it was written correctly (easy to check by opening it in a text editor); but MS Excel (or Gnumeric or Open/Libre Office) always formats numbers to a standardised format when importing a CSV file, so it isn't possible to store masking details such as leading zeroes, etc in a CSV format file.

One option is to wrap formatted numbers in quotes so they will be treated as a string, e.g

"001234.56"

But if you want consistent formatting for opening in a spreadsheet program, you really need to use a native format such as BIFF, OfficeOpenXML or OASIS

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Are the zeroes even gone from the raw file, for example. excel removes leading zeros, but they are still in the raw file.

ThatsRight
  • 175
  • 7