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

前端 未结 6 1516
时光取名叫无心
时光取名叫无心 2021-01-01 14:58

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(,)

6条回答
  •  心在旅途
    2021-01-01 15:21

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

提交回复
热议问题