C# 在 .net 中写入 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1684667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a CSV file in .net
提问by Russell
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.
我花了一段时间寻找一套规则,并意识到在编写 CSV 文件时有很多规则和例外。
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
http://knab.ws/blog/index.php?/archives/3-CSV-file-parser-and-writer-in-C-Part-1.html http://bytes.com/topic/c- sharp/answers/236875-problems-streamwriter-output-csv http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/0073fcbb-adab-40f0-b768-4bba803d3ccd
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.
所以现在这不是用逗号分隔字符串的简单过程,我已经搜索了 3rd 方或(希望!)包含在 .net 框架中的现有 CSV 编写器。
Edit: New link: http://www.thinqlinq.com/Post.aspx/Title/LINQ-to-CSV-using-DynamicObject-and-TextFieldParser
编辑:新链接:http: //www.thinqlinq.com/Post.aspx/Title/LINQ-to-CSV-using-DynamicObject-and-TextFieldParser
The TextFieldParser is a VB object (can be referenced from C#) that will automatically parse CSV files. :)
TextFieldParser 是一个 VB 对象(可以从 C# 引用),它将自动解析 CSV 文件。:)
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 文件的任何方便的 .Net(2.0 -> 3.5 和 4.0)库。
Also, if there are any sets of rules for generating CSV files.
此外,如果有任何用于生成 CSV 文件的规则集。
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 ).
有很多关于 CSV 阅读器和解析 CSV 文件的细节,但关于写作的细节并不多(好吧,我知道恰恰相反 :P )。
http://www.codeproject.com/KB/database/CsvReader.aspx
http://www.codeproject.com/KB/database/CsvReader.aspx
Any help would be much appreciated :)
任何帮助将非常感激 :)
I found another article with some more detailed CSV rules: http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
我发现了另一篇包含更详细 CSV 规则的文章:http: //www.creativyst.com/Doc/Articles/CSV/CSV01.htm
A neat 3rd party library is Linq-to-CSV (not framework library): http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
一个整洁的 3rd 方库是 Linq-to-CSV(不是框架库):http: //www.codeproject.com/KB/linq/LINQtoCSV.aspx
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).
谢谢大家的帮助。我决定最好的解决方案是创建一个简单的静态类来进行特殊字符替换(Chris 提到过)。
If I had a need for Linq querying my CSV files, I would look at the CodeProjects implementation of Linq-to-CSV.
如果我需要 Linq 查询我的 CSV 文件,我会查看 Linq-to-CSV 的 CodeProjects 实现。
Thanks again :)
再次感谢 :)
采纳答案by Chris
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
As for dates, stick to ISO format, and you should be fine (eg yyyy-mm-dd hh:mm:ss)
至于日期,坚持 ISO 格式,你应该没问题(例如 yyyy-mm-dd hh:mm:ss)
回答by lomaxx
I've used filehelpersextensively and it's pretty awesome for generating CSVs.
我已经广泛使用了文件助手,它非常适合生成 CSV。
回答by itowlson
You can use ODBC to read and write CSV files (via OdbcConnection and a suitable connection string). This should be reasonably good for generating CSV files, and will handle things like quoting for you; however I have run into some issues when using it to read CSV files generated by other programs.
您可以使用 ODBC 读取和写入 CSV 文件(通过 OdbcConnection 和合适的连接字符串)。这对于生成 CSV 文件应该相当不错,并且会为您处理诸如引用之类的事情;但是我在使用它读取其他程序生成的 CSV 文件时遇到了一些问题。
回答by Russell
I found this important link which is quite neat. Haven't tried it yet, will let you know how it goes!
我发现这个重要的链接非常整洁。还没试过,会告诉你结果如何!
http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
Looking more closely, this implementation essentially only uses basic rules too:
仔细观察,这个实现基本上也只使用基本规则:
special chars = \n \" and the separator char.
特殊字符 = \n \" 和分隔符。
if found special characters, then surround with quotes. Replace quote with double quote.
如果找到特殊字符,则用引号括起来。用双引号替换引号。
Essentially the rules Chris mentioned. I think the easiest way to do this is to create my helper method based on the simple rules and revise on a user-needs basis.
基本上就是克里斯提到的规则。我认为最简单的方法是根据简单的规则创建我的辅助方法并根据用户需要进行修改。
回答by dan-gph
Another rule to add to the others: Use the commas as field separators rather than as field terminators. The reason for this is that a trailing comma at the end of a line could be ambiguous: Does it have no significance or does it signify a NULL value following it?
添加到其他规则的另一个规则:使用逗号作为字段分隔符而不是字段终止符。这样做的原因是行尾的尾随逗号可能不明确:它没有意义还是表示它后面有一个 NULL 值?
回答by TrueWill
For the specifications, see http://en.wikipedia.org/wiki/Comma-separated_values
有关规格,请参阅 http://en.wikipedia.org/wiki/Comma-separated_values
回答by super_seabass
I know you said you found your answer, but I just wanted to give a vote for the LINQtoCSV library you mentioned. I've used it in a couple projects and it works really well for keeping your business code clean and not concerned with details / peculiarities of the file format.
我知道您说过您找到了答案,但我只是想为您提到的 LINQtoCSV 库投上一票。我已经在几个项目中使用过它,它可以很好地保持您的业务代码干净,并且不关心文件格式的细节/特性。
Maybe in your specific case it is not too difficult to write the exporter, but the nice thing about this library is that it is bidirectional. If you find yourself having to consume the CSV down the road it's not much extra code, and/or it gives you a consistent library to use on future projects.
也许在您的特定情况下,编写导出器并不太难,但是这个库的好处在于它是双向的。如果您发现自己必须在路上使用 CSV,那么它不会有太多额外的代码,和/或它为您提供了一个一致的库以用于未来的项目。
回答by Richard Nienaber
回答by Josh Close
CsvHelper(a library I maintain) also available via NuGet.
CsvHelper(我维护的一个库)也可以通过 NuGet 获得。
CsvHelper can automatically write your class objects to a file for you.
CsvHelper 可以自动将您的类对象写入文件。
var myObj = new MyCustomClass
{
Prop1 = "one",
Prop2 = 2
};
var streamWriter = // Create a writer to somewhere...
var csvWriter = new CsvWriter( streamWriter );
// You can write a single record.
csvWriter.WriteRecord( myObj );
// You can also write a collection of records.
var myRecords = new List<MyCustomClass>{ myObj };
csvWriter.WriteRecords( myRecords );
回答by user291066
Can you use a string array and then concatenate using:
您可以使用字符串数组,然后使用以下方法连接:
string out = "";
string[] elements = { "1", "2" };
foreach(string s in elements) { out += s + "," };
out = out.substring(0, out.Length-1);