Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - format column when writing to CSV file(cell formatting)

Tags:

string

c#

.net

Have written the method for the exporting the data to csv files. If the value of the cell has DEC20 in csv is getting as 20-Dec which is not correct.

My code is like this:

for (int i = 0; i < myData.Count(); i++)
{
    sb.AppendLine(string.Join(delimiter, 
                              Common.FormatExportString(myData[i].Code),
                              Common.FormatExportString(myData[i].Name),
                              Common.FormatExportString(myData[i].Description)));
}
//returns the file after writing the stream to the csv file.
return File(new System.Text.UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);

Kindly help me to get the exact string format to be displayed in the excel (csv) file using C#.

Ex: myData[i].Name data will be

DEC20, or 2-5

like this,

but the output in csv(excel) is getting displayed as

20-Dec and 5-May

instead of the original one.

like image 553
Karthika Subramanian Avatar asked Dec 07 '22 10:12

Karthika Subramanian


1 Answers

The problem is not concerning the csv exportation, if you open the csv file with notepad it is well formed. It is Excel that auto-detects the cell type as a date and shows it as a date.

To avoid this behavior wrap the text between quotes and put a = before it, as shown below:

= "DEC20"

The file should became as

= "field1", = "field2", = "field...", = "DEC20", ...

Your method should become:

for (int i = 0; i < myData.Count(); i++)
{
    sb.AppendLine(string.Join(delimiter, 
                              " = \"",
                              Common.FormatExportString(myData[i].Code),
                              Common.FormatExportString(myData[i].Name),
                              Common.FormatExportString(myData[i].Description)
                              "\""));
}

//returns the file after writing the stream to the csv file.
return File(new System.Text.UTF8Encoding().GetBytes(sb.ToString()), "text/csv", fileName);
like image 120
Tobia Zambon Avatar answered Dec 19 '22 11:12

Tobia Zambon