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

China☆狼群 提交于 2019-11-29 11:22:46

问题


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?


回答1:


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




回答2:


  1. Fields with embedded commas must be delimited with double-quote characters.

    fields:

    1. abc, xyz
    2. pqr

csv version:

"abc, xyz" , pqr
  1. Fields that contain double quote characters must be surounded by double-quotes, and the embedded double-quotes must each be represented by a pair of consecutive double quotes.

    field:

    Welcome to "My World"
    

    csv version:

    "Welcome to ""My World"""
    



回答3:


If you have a comma in the data you need to put in a csv the http://tools.ietf.org/html/rfc4180 says to use quotations as:

"123,56","A dog, cat and a frog"



回答4:


Write Comma separated value between double quote without space to create csv with single column for comaa separated values.

Ex. I have two columns Code & Description With Values Code01 & Val1,Val2,Val3. To create csv with given data write below line in notepad and save it with csv extension.

Code,Description
Code01,"Val1,Val2,Val3"



回答5:


StringBuilder sb = new StringBuilder();          
        foreach (DataColumn col in dt.Columns)
        {
            if (col.ColumnName.Contains(","))
            {
                sb.Append(String.Format("\"{0}\",", col.ColumnName));
            }
            else
            {
                sb.Append(String.Format("{0},", col.ColumnName));
            }
        }



回答6:


Put Value in double quotes.

string ValueToEscape = "a,b";

"\"" + ValueToEscape + "\""

CSV Output = a,b



来源:https://stackoverflow.com/questions/8090759/how-to-write-a-value-which-contain-comma-to-a-csv-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!