在日常开发中使用CSV文件进行数据导入和导出、数据交换是非常常见的需求,以下来讲讲在DotNet中如何使用CsvHelper这个开源库快速实现CSV文件读取和写入,需要的朋友可以参考下
CsvHelper类库介绍
CsvHelper是一个.NET开源、快速、灵活、高度可配置、易于使用的用于读取和写入CSV文件的类库。
什么是 .csv 文件?
.csv 文件是一种用于存储表格数据的文本文件,CSV 是 "Comma-Separated Values" 的缩写,意思是 "逗号分隔值"。CSV 文件是一个存储表格和电子表格信息的纯文本文件,其内容通常是一个文本、数字或日期的表格。CSV 文件可以使用以表格形式存储数据的程序轻松导入和导出。
创建控制台应用
创建一个名为:CsvHelperExercise
的.NET 8控制台应用。
安装CsvHelper类库
NuGet包管理器中搜索:CsvHelper
,点击安装!
定义CSV文件读取和写入的对象
public class StudentInfo{/// <summary>/// 学生学号/// </summary>public int ID { get; set; }/// <summary>/// 学生姓名/// </summary>public string Name { get; set; }/// <summary>/// 学生年龄/// </summary>public int Age { get; set; }/// <summary>/// 班级/// </summary>public string Class { get; set; }/// <summary>/// 性别/// </summary>public string Gender { get; set; }/// <summary>/// 住址/// </summary>public string Address { get; set; }}
写入CSV文件数据
static void Main(string[] args){var students = new List<StudentInfo>{new StudentInfo { ID = 1, Name = "张三", Age = 20, Class = "终极一班", Gender = "男", Address = "北京市东城区" },new StudentInfo { ID = 2, Name = "李四", Age = 21, Class = "终极一班", Gender = "女", Address = "上海市黄浦区" },new StudentInfo { ID = 3, Name = "王五", Age = 22, Class = "终极一班", Gender = "男", Address = "广州市越秀区" },new StudentInfo { ID = 4, Name = "赵六", Age = 20, Class = "终极二班", Gender = "女", Address = "深圳市福田区" },new StudentInfo { ID = 5, Name = "孙七", Age = 23, Class = "终极二班", Gender = "男", Address = "杭州市西湖区" },new StudentInfo { ID = 6, Name = "周八", Age = 24, Class = "终极二班", Gender = "女", Address = "南京市玄武区" },new StudentInfo { ID = 7, Name = "吴九", Age = 22, Class = "终极二班", Gender = "男", Address = "成都市锦江区" },new StudentInfo { ID = 8, Name = "小袁", Age = 21, Class = "终极三班", Gender = "女", Address = "重庆市渝中区" },new StudentInfo { ID = 9, Name = "大姚", Age = 20, Class = "终极三班", Gender = "男", Address = "武汉市武昌区" },new StudentInfo { ID = 10, Name = "独孤求败", Age = 23, Class = "终极三班", Gender = "女", Address = "长沙市天心区" }};//写入CSV文件数据using var writer = new StreamWriter(@".\StudentInfoFile.csv");using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture);csvWriter.WriteRecords(students);}
读取CSV文件数据
快速读取上面写入到StudentInfoFile.csv
中的数据。
static void Main(string[] args){//读取CSV文件数据using var reader = new StreamReader(@".\StudentInfoFile.csv");using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);var getStudentInfos = csvReader.GetRecords<StudentInfo>().ToList();}