起因: 最近做了好几个导出/导入 CSV 文件的功能,之前用的是 Stackoverflow 上找的一段代码,做的多了,就想有没有什么好用的包,于是就发现了 CsvHelper。
优势
- 易于映射 CSV 文件为实体类
- 更新积极
- 文档丰富,示例清晰
- 商用无限制
简介
CsvHelper 是一个用于读取和写入 CSV 文件的 .NET 库。 快速、灵活且易于使用。A .NET library for reading and writing CSV files. Extremely fast, flexible, and easy to use.
相关资源:
支持平台:
- NET Framework (4.5 and higher)
- .NET Standard (2.0 and higher)
使用
初步上手
参考官方的 Getting Started 即可。
CSV 文件:
Id,Name1,one2,two
实体类定义:
public class Foo{public int Id { get; set; }public string Name { get; set; }}
读取 CSV 文件为 IEnumerable<T>:
using (var reader = new StreamReader("path\\to\\file.csv"))using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)){var records = csv.GetRecords<Foo>();}
注意事项
当你没有为实体类定义构造函数时,须保证 CSV 文件的列标题与属性名称一致。
若你为实体类定义了构造函数,则须保证 CSV 文件的列标题与构造函数的形参名称一致。
