使用 C# 写入 CSV 文件
我正在寻找一种在 CSV 文件的不同单元格中写入字符串的方法。
我正在使用这个程序,
private void button1_Click(object sender, EventArgs e)
{
string filePath = @"E:\test.csv";
string a = "a";
string b = "c";
string c = "d";
string d = "d";
File.WriteAllText(filePath, a);
// how can add the other strings in the next cells ?
}
我在这里需要的是在第一个单元格中写入“a”,在第二个单元格中写入“b”,c ..
I'm looking for a way to write strings in a different cell of a CSV file.
I'm using this program,
private void button1_Click(object sender, EventArgs e)
{
string filePath = @"E:\test.csv";
string a = "a";
string b = "c";
string c = "d";
string d = "d";
File.WriteAllText(filePath, a);
// how can add the other strings in the next cells ?
}
What I need here is to write "a" in the first cell, "b" in the second cell, c ..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
CSV 是一种非常简单的文件格式,特别是当您不需要任何单元格包含嵌套逗号时。 CSV 表示逗号分隔值,因此您只需要一种方法来构造一个在每个单元格之间使用逗号的字符串。这将起作用,尽管它仅适用于单行:
CSV is a pretty simple file format, especially if you don't need any cells to contain nested commas. CSV means comma-separated values, so you just need a way to construct a string with commas between each cell. This will work, although it is only for a single line:
CSV 绝对不是一种简单的文件格式,它是一种足够复杂的格式,能够包含几乎任何类型的数据,无论形状或大小如何。
CSV 格式能够处理可选参数与非可选参数、带或不带换行符的数据,并且应该能够在任何不带换行符的字段中使用或不使用字段转义字符,并且需要在带换行符的字段中包含字段转义字符换行符。
您不应该手动处理 CSV 文件,您应该使用 FileHelpers 来处理 CSV 文件。
此时,我不再使用 FileHelpers 作为我的 goto CSV 解析库,而是使用 Josh Close 的 CsvHelper 。
CSV is absolutely NOT a SIMPLE file format, it is a sufficiently elaborate format that is able to encompass almost any kind of data regardless of shape or size.
The CSV format is capable of dealing with optional parameters vs non optional, data with or without line breaks, and should be able to work with or without field escaping characters in any field without line breaks and is required to have field escaping characters in fields with line breaks.
You should not ever work with CSV files by hand, you should utilize FileHelpers to work with CSV files.
At this point I no longer use FileHelpers as my goto CSV parsing library I use CsvHelper from Josh Close.
如果只有 4 个值,并且只有一行呢? (我认为情况并非如此?)
如果数据基于某种集合,请提供更多信息。
If there are only 4 values, and a single row? (Which I assume is not the case?)
If the data is based on some sort of collection, give some more info.