Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a value which contain comma to a CSV file in c#?

Tags:

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.

For Example

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?

like image 584
user1027129 Avatar asked Nov 11 '11 07:11

user1027129


People also ask

How do I convert a comma separated value to a CSV file?

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.

Can CSV values have commas?

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.

How do you handle commas in data when exporting to a CSV file in C?

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.


1 Answers

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 ","

like image 159
Anh Hoang Avatar answered Oct 04 '22 04:10

Anh Hoang