引用 CSVHelper
Install-Package CsvHelper -Version 30.0.1
创建工具类
public class CsvUtility { /// <summary> /// Read csv file /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path">The complete file path to read to.</param> /// <param name="hasHeader">Whether the file has a header.</param> /// <returns>Return T collections.</returns> public static List<T> ReadCSV<T>(string path, bool hasHeader) { var config = new CsvConfiguration(CultureInfo.InvariantCulture) { HasHeaderRecord = hasHeader, }; using (var reader = new StreamReader(path, Encoding.UTF8)) { using (var csv = new CsvReader(reader, config)) { return csv.GetRecords<T>().ToList(); } } } /// <summary> /// Write csv file /// </summary> /// <param name="path">The complete file path to write to.</param> /// <param name="data">The records of csv file.</param> /// <param name="hasHeader">Whether the file has a header.</param> public static void WriteToCSV<T>(string path, List<T> data, bool hasHeader) { var config = new CsvConfiguration(CultureInfo.InvariantCulture) { HasHeaderRecord = hasHeader, }; using (var writer = new StreamWriter(path, false, System.Text.Encoding.UTF8)) { using (var csv = new CsvWriter(writer, config)) { csv.WriteRecords(data); } } } }
定义数据模型
CsvHelper.Configuration.Attributes.Name 用来写入文件标头,如果没有写入标头的需求也可以不需要设置
public class CsvModel { [CsvHelper.Configuration.Attributes.Name("Id")] public int Id { get; set; } [CsvHelper.Configuration.Attributes.Name("Full Name")] public string Name { get; set; } }
测试写入csv文件
List<CsvModel> data = new List<CsvModel>() { new CsvModel { Id=1, Name="John" }, new CsvModel { Id=2, Name="Admin" } }; CsvUtility.WriteToCSV<CsvModel>("no-header.csv", data, false); CsvUtility.WriteToCSV<CsvModel>("has-header.csv", data, true);
List<CsvModel> data1 = CsvUtility.ReadCSV<CsvModel>("no-header.csv", false); List<CsvModel> data2 = CsvUtility.ReadCSV<CsvModel>("has-header.csv", true);