Including leading zeros in numeric data when exporting data to Excel CSV text format

Posted: (EET/GMT+2)

 

In ASP.NET web applications, you often find yourself in the situation where data needs to be outputted in Excel format. The easiest way to do this by far the text-based CSV format, which is also a format that can be directly opened in Excel.

However, when you export leading zeros into a CSV file and open the file in Excel, Excel automatically strips out the leading zeros, so that the number "00010" will become just "10". When you enter data directly in Excel, you can type the single quote character ' in front of the number, but this doesn't work with CSV files. Similarly, using quotes around the number will not work

Luckily, there's a nifty trick that you can use: if you enter the number as a simple formula in the CSV file, the leading zeros will be preserved. Here's how you can use this trick:

=”00010”

When you prefix the number with the equal sign and put quotes around it, Excel preserves the leading zeros.

Problem solved!