Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a CSV so that a numeric appears as a string in the spreadsheet?

Tags:

c#

csv

excel

I am trying to build an application that extracts some data from a database, and then uses some of the data to create a CSV file to be loaded up by Excel. The codez:

foreach (xOFDocInfo cm in docs)
{
    string s = bi.Agency
        + "," + cm.BatNbr.Trim()
        + "," + cm.RefNbr
        + "," + cm.DocType
        + "," + cm.OrigDocAmt.ToString()
        + "," + cm.CreateDate.ToShortDateString();

    writer.WriteLine(s);

}

The "cm.BatNbr" is a 6 character zero-filled numeric such as "001234". I want Excel to format that column as text so I don't lose the zeroes up front. I've tried some tricks, such as prefixing the number with a single-quote (apostrophe), but all I get is an apostrophe prefix. If I set the cells to be formatted as text then remove the apostrophes, I also lose the zeroes at the front.

I accidentally found that if I prefix the thing with a percent sign, Excel converts the value in the cell to a percentage, so perhaps there is some prefix I can use to cause Excel to take the value in the cell as text when I load it up?

like image 873
Cyberherbalist Avatar asked Mar 22 '11 22:03

Cyberherbalist


People also ask

How do I save a number as text in a CSV file?

Export data to a text file by saving it Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

How do I keep my numbers formatted in CSV?

To preserve all the digits in text-formatted numbers, you have to import the downloaded CSV file as raw data into a new Excel spreadsheet, set the column datatypes as needed, and then save the new file as an Excel workbook. Excel (XLSX) files will preserve these formats, CSV files won't.

How do I create a CSV delimiter in Excel?

csv file, Excel separates values with your default List separator. To force it to use a different delimiter, proceed with the following steps: Click File > Options > Advanced. Under Editing options, clear the Use system separators check box.

Are CSV values strings?

CSV is string data. If your data is normalized you can do things like attempt to convert to a numeric; if it works, it's a number, if it fails, it's a string. It will fail.


1 Answers

You could format the data as ="001234". This will cause Excel to display it as 001234.

foreach (xOFDocInfo cm in docs)
{
    string s = bi.Agency
        + ",=\"" + cm.BatNbr.Trim()
        + "\"," + cm.RefNbr
        + "," + cm.DocType
        + "," + cm.OrigDocAmt.ToString()
        + "," + cm.CreateDate.ToShortDateString();

    writer.WriteLine(s);

}

You could also try using the SYLK format instead of CSV. SYLK gives you better control over formatting.

like image 190
Greg Avatar answered Oct 05 '22 13:10

Greg