I am using a data table for storing data.
I am exporting the data from data table to CSV file.
Sometimes there may be values containing comma(,
) so the values are not exported correctly.
Consider the value is "9,11,32"
. I have to export as such.
But when I do the first column conatins 9
then in next column 11
.
I want to display 9,11,32
in the same column in the CSV file. How do I do that?
A CSV file contains a set of records separated by a carriage return/line feed (CR/LF) pair ( \r\n ), or by a line feed (LF) character. Each record contains a set of fields separated by a comma. If the field contains either a comma or a CR/LF, the comma must be escaped with double quotation marks as the delimiter.
A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
Re: Handling 'comma' in the data while writing to a CSV. So for data fields that contain a comma, you should just be able to wrap them in a double quote. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
Simply put your data inside the backslash like this: "\"" + yourdata + "\"". Take a look on the example below:
StringWriter csv = new StringWriter(); // Generate header of the CSV file csv.WriteLine(string.Format("{0},{1}", "Header 1", "Header 2")); // Generate content of the CSV file foreach (var item in YourListData) { csv.WriteLine(string.Format("{0},{1}", item.Data1, "\"" + item.Data2 + "\"")); } return File(new System.Text.UTF8Encoding().GetBytes(csv.ToString()), "application/csv", string.Format("{0}{1}", "YourFileName", ".csv"));
In the example: Your data2 may contains comma ","
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