[英]How to write csv format compatible with Microsoft.VisualBasic.FileIO.TextFieldParser?
I use Microsoft.VisualBasic.FileIO.TextFieldParser to parse csv files.我使用Microsoft.VisualBasic.FileIO.TextFieldParser来解析 csv 文件。
I'd now know like to export some data to csv format.我现在知道想将一些数据导出为 csv 格式。 For consistency on the difficult csv behaviours (quoting, escaping, etc) I'd like to use the same class or a similar one - ideally in the standard library, so that I can trust to be compatible.
为了在困难的 csv 行为(引用、转义等)上保持一致性,我想使用相同的类或类似的类 - 理想情况下在标准库中,这样我就可以相信兼容。
How can I do that?我怎样才能做到这一点?
Edit: My data to export is List<List<string>>
编辑:我要导出的数据是
List<List<string>>
TextFieldParser
can only be used to read structured text files, such as CSV files. TextFieldParser
只能用于读取结构化文本文件,例如 CSV 文件。
In order to write, I suggest using File Helpers , which can also be used to read CSV files (so can be an altogether replacement).为了写入,我建议使用File Helpers ,它也可以用于读取 CSV 文件(因此可以完全替代)。
The characters that are escaped in standard CSV are Tab, CR, LF, double quote, and comma:在标准 CSV 中转义的字符是 Tab、CR、LF、双引号和逗号:
char[] chars = { '\t', '\r', '\n', '\"', ',' };
if (stringField.IndexOfAny(chars) >= 0)
{
stringField = '\"' + stringField.Replace("\"", "\"\"") + '\"'; // replace " with ""
}
It can easily be tested with Excel or copying from a DataGridView
control.它可以很容易地使用 Excel 进行测试或从
DataGridView
控件中复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.