C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件

引用 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);


测试读取csv文件
List<CsvModel> data1 = CsvUtility.ReadCSV<CsvModel>("no-header.csv", false);
List<CsvModel> data2 = CsvUtility.ReadCSV<CsvModel>("has-header.csv", true);


作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角