在日常开发中使用CSV文件进行数据导入和导出、数据交换是非常常见的需求,今天我们来讲讲在.NET中如何使用CsvHelper这个开源库快速实现CSV文件读取和写入。
CsvHelper是一个.NET开源、快速、灵活、高度可配置、易于使用的用于读取和写入CSV文件的类库。
图片
图片
.csv 文件是一种用于存储表格数据的文本文件,CSV 是 "Comma-Separated Values" 的缩写,意思是 "逗号分隔值"。CSV 文件是一个存储表格和电子表格信息的纯文本文件,其内容通常是一个文本、数字或日期的表格。CSV 文件可以使用以表格形式存储数据的程序轻松导入和导出。
创建一个名为:CsvHelperExercise的.NET 8控制台应用。
图片
图片
图片
NuGet包管理器中搜索:CsvHelper,点击安装!
图片
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; } }
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); }
图片
快速读取上面写入到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(); }
图片
更多项目实用功能和特性欢迎前往项目开源地址查看
本文链接://www.dmpip.com//www.dmpip.com/showinfo-26-96431-0.html.NET使用CsvHelper快速读取和写入CSV文件
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com