Home > database >  Force text format in CSV in C#
Force text format in CSV in C#

Time:10-29

I am trying to write to a CSV file and one of the fields contains a value like 20190618160442.983. This value is declared varchar in the table I am pulling the data from and is converted using ToString() in the app I created but when I open the CSV in Excel, Excel rounds the value and converts it to scientific notation. Is there a way in C# to force this value to remain text when I open it in Excel? I am using

                sb.AppendLine(string.Join(",", fields));

to build each row in the CSV.

Thanks in advance for any suggestions.

CodePudding user response:

This is a bit hacky, but if you want to deal with those values as text on initial load, you can prepend the values of those fields with =""&. Or wrap the value with =" and ". Eg CSV:

Value for column 1,=""&20190618160442.983

or

Value for column 1,="20190618160442.983"

output:

screenshot from Excel

This will cause Excel to interpret the incoming CSV value as an expression with a string output, so display as string. If it's just for display, fine, but it may not work for your purposes.

CodePudding user response:

CSV files contain data only. They don't provide any information about formatting. And there is no way to control that from the CSV file.

The solution is to either format it in Excel, or create a true Excel (XLSX) file, which is a fair amount of work.

  •  Tags:  
  • c#
  • Related