在 .net 中写入 CSV 文件
我需要将数据集导出为 CSV 文件.
I have a requirement to export a dataset as a CSV file.
我花了一段时间寻找一套规则,并意识到在编写 CSV 文件时有很多规则和例外.
I have spent a while searching for a set of rules to go by and realised there are quite a few rules and exceptions when writing a CSV file.
http://knab.ws/blog/index.php?/archives/3-CSV-file-parser-and-writer-in-C-Part-1.htmlhttp://bytes.com/topic/c-sharp/answers/236875-problems-streamwriter-output-csvhttp://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/0073fcbb-adab-40f0-b768-4bba803d3ccd
所以现在这不是用逗号分隔字符串的简单过程,我已经搜索了 3rd 方或(希望!)包含在 .net 框架中的现有 CSV 编写器.
So now it is not a simple process of separating strings with commas, I have searched for an existing CSV writer either 3rd party or (hopefully!) included in the .net framework.
新链接:http://www.thinqlinq.com/Post.aspx/Title/LINQ-to-CSV-using-DynamicObject-and-TextFieldParser
TextFieldParser 是一个 VB 对象(可以从 C# 引用),它将自动解析 CSV 文件.:)
The TextFieldParser is a VB object (can be referenced from C#) that will automatically parse CSV files. :)
我想知道是否有人知道可用于生成格式正确的 CSV 文件的任何方便的 .Net(2.0 -> 3.5 和 4.0)库.
I was wondering if anybody knows any handy .Net (2.0 -> 3.5 and 4.0) libraries that can be used to generate a correctly formatted CSV file.
另外,如果有任何生成 CSV 文件的规则集.
Also, if there are any sets of rules for generating CSV files.
有很多关于 CSV 阅读器和解析 CSV 文件的细节,但是关于写作的细节不多(好吧,我知道恰恰相反:P).
There are a lot of details of CSV readers and parsing CSV files, however not as many about writing (ok, I know it is just the opposite :P ).
http://www.codeproject.com/KB/database/CsvReader.aspx
任何帮助将不胜感激:)
Any help would be much appreciated :)
我发现了另一篇文章,其中包含一些更详细的 CSV 规则:http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
I found another article with some more detailed CSV rules: http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
一个简洁的 3rd 方库是 Linq-to-CSV(不是框架库):http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
A neat 3rd party library is Linq-to-CSV (not framework library): http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
感谢大家的帮助.我决定最好的解决方案是创建一个简单的静态类来进行特殊字符替换(Chris 提到过).
Thanks for your help everyone. I have decided that the best solution will be to create a simple static class that will do the special character replacement (that Chris mentioned).
如果我需要 Linq 查询我的 CSV 文件,我会查看 Linq-to-CSV 的 CodeProjects 实现.
If I had a need for Linq querying my CSV files, I would look at the CodeProjects implementation of Linq-to-CSV.
再次感谢:)
如果您的单元格中有逗号,请用双引号将整个单元格括起来,例如:
If there are any commas in your cell, surround the entire cell with double quotes, eg:
cell 1,cell 2,"This is one cell, even with a comma",cell4,etc
如果你想要一个文字双引号,做其中两个,例如:
And if you want a literal double quote, do two of them, eg:
cell 1,cell 2,"This is my cell and it has ""quotes"" in it",cell 4,etc
至于日期,坚持ISO格式,你应该没问题(例如yyyy-mm-dd hh:mm:ss)
As for dates, stick to ISO format, and you should be fine (eg yyyy-mm-dd hh:mm:ss)