简体   繁体   English

导出为CSV - C#

[英]Exporting to CSV - C#

I need to export a generic list to CSV. 我需要将通用列表导出为CSV。 Obviously I could write my own, but would like to avoid this! 显然我可以写自己的,但想避免这个!

I am able to google and find a lot of CSV parsers, but not many writers. 我能够google并找到很多CSV解析器,但编写器并不多。 I have downloaded FileHelpers but it doesn't properly escape output. 我已经下载了FileHelpers但它没有正确地转义输出。

For instance if a field is equal to 例如,如果字段等于

,,",,,

the output is simply: 输出很简单:

,,",,,

For the field. 对于该领域。 I would expect: 我希望:

",,"",,,"

correct? 正确?

Any suggestions, or should I just do it myself? 有什么建议,还是我应该自己做?

Check out RFC 4180. I had to write a XSL to convert XML to CSV and this made it very easy to know what the 'right' thing is to do. 查看RFC 4180.我必须编写一个XSL来将XML转换为CSV,这使得很容易知道“正确”的事情是做什么的。

http://tools.ietf.org/rfc/rfc4180.txt http://tools.ietf.org/rfc/rfc4180.txt

FileHelpers将使用记录映射类中字段的FieldQuoted属性执行您所要求的操作

With how simple it is to make your own, I say write you own class for this. 制作自己的简单是多么简单,我说为此写自己的课程。 You could handle any nuances on your own pretty easily. 你可以很容易地处理自己的细微差别。

I can really recommend CsvHelper by Josh Close for reading and writing csv format. 我真的可以推荐Josh Close的CsvHelper阅读和编写csv格式。 CsvHelper will handle most common use cases, including escaping of strings with special characters. CsvHelper将处理大多数常见用例,包括转义带有特殊字符的字符串。

You can use simple methods to read and write (lists of) objects or manually read/write any field you want. 您可以使用简单的方法来读取和写入(列表)对象,也可以手动读取/写入您想要的任何字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM