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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With