如何在C#中将包含逗号的值写入CSV文件? [英] How to write a value which contain comma to a CSV file in c#?

查看:368
本文介绍了如何在C#中将包含逗号的值写入CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用数据表来存储数据.

I am using a data table for storing data.

我正在将数据从数据表导出到CSV文件.

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.

请考虑值为"9,11,32".我必须这样出口.

Consider the value is "9,11,32". I have to export as such.

但是当我做第一列conatins 9时,然后在下一列11中.

But when I do the first column conatins 9 then in next column 11.

我想在CSV文件的同一列中显示9,11,32.我该怎么办?

I want to display 9,11,32 in the same column in the CSV file. How do I do that?

推荐答案

只需将您的数据放在反斜杠内,如下所示:"\""+ yourdata +" \".看下面的例子:

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"));

在示例中:您的data2可能包含逗号,"

In the example: Your data2 may contains comma ","

这篇关于如何在C#中将包含逗号的值写入CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆