Numeric fields lose leading zero while writing CSV in c#

Change the data that is saved in the csv with the following format:

 ="00023423"

CSV example:

David,Sooo,="00023423",World

This will show 00023423 in excel and not 23423.


public void CreatingCsvFiles(Client client)
    {
        string filePath = "Your path of the location" + "filename.csv";
        if (!File.Exists(filePath))
        {
            File.Create(filePath).Close();
        }
        string delimiter = ",";
        string[][] output = new string[][]{
        new string[]{ "=\"" + client.phone + "\"", client.name }
        };
        int length = output.GetLength(0);
        StringBuilder sb = new StringBuilder();
        for (int index = 0; index < length; index++)
        sb.AppendLine(string.Join(delimiter, output[index]));
        File.AppendAllText(filePath, sb.ToString());
    }

Inspired from http://softwaretipz.com/c-sharp-code-to-create-a-csv-file-and-write-data-into-it/

The important part :

  "=\"" + client.phone + "\"", client.name

If the phone number is an int, of course you add .toString().


Print phone number to CSV with prepended ' (single quote), so it looks like:

"Some Name","'0000121212"

Excel should treat this 0000121212 as string then.

Tags:

C#

Csv