前言
在日常開發(fā)中使用CSV文件進(jìn)行數(shù)據(jù)導(dǎo)入和導(dǎo)出、數(shù)據(jù)交換是非常常見的需求,今天我們來講講在.NET中如何使用CsvHelper
這個(gè)開源庫快速實(shí)現(xiàn)CSV文件讀取和寫入。
CsvHelper類庫介紹
CsvHelper是一個(gè).NET開源、快速、靈活、高度可配置、易于使用的用于讀取和寫入CSV文件的類庫。
CsvHelper類庫特點(diǎn)
什么是 .csv 文件?
.csv 文件是一種用于存儲表格數(shù)據(jù)的文本文件,CSV 是 "Comma-Separated Values" 的縮寫,意思是 "逗號分隔值"。CSV 文件是一個(gè)存儲表格和電子表格信息的純文本文件,其內(nèi)容通常是一個(gè)文本、數(shù)字或日期的表格。CSV 文件可以使用以表格形式存儲數(shù)據(jù)的程序輕松導(dǎo)入和導(dǎo)出。
創(chuàng)建控制臺應(yīng)用
創(chuàng)建一個(gè)名為:CsvHelperExercise
的.NET 8控制臺應(yīng)用。
安裝CsvHelper類庫
NuGet包管理器中搜索:CsvHelper
,點(diǎn)擊安裝!
定義CSV文件讀取和寫入的對象
public class StudentInfo
{
/// <summary>
/// 學(xué)生學(xué)號
/// </summary>
public int ID { get; set; }
/// <summary>
/// 學(xué)生姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 學(xué)生年齡
/// </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文件數(shù)據(jù)
static void Main(string[] args)
{
var students = new List<StudentInfo>
{
new StudentInfo { ID = 1, Name = "張三", Age = 20, Class = "終極一班", Gender = "男", Address = "北京市東城區(qū)" },
new StudentInfo { ID = 2, Name = "李四", Age = 21, Class = "終極一班", Gender = "女", Address = "上海市黃浦區(qū)" },
new StudentInfo { ID = 3, Name = "王五", Age = 22, Class = "終極一班", Gender = "男", Address = "廣州市越秀區(qū)" },
new StudentInfo { ID = 4, Name = "趙六", Age = 20, Class = "終極二班", Gender = "女", Address = "深圳市福田區(qū)" },
new StudentInfo { ID = 5, Name = "孫七", Age = 23, Class = "終極二班", Gender = "男", Address = "杭州市西湖區(qū)" },
new StudentInfo { ID = 6, Name = "周八", Age = 24, Class = "終極二班", Gender = "女", Address = "南京市玄武區(qū)" },
new StudentInfo { ID = 7, Name = "吳九", Age = 22, Class = "終極二班", Gender = "男", Address = "成都市錦江區(qū)" },
new StudentInfo { ID = 8, Name = "小袁", Age = 21, Class = "終極三班", Gender = "女", Address = "重慶市渝中區(qū)" },
new StudentInfo { ID = 9, Name = "大姚", Age = 20, Class = "終極三班", Gender = "男", Address = "武漢市武昌區(qū)" },
new StudentInfo { ID = 10, Name = "追逐時(shí)光者", Age = 23, Class = "終極三班", Gender = "女", Address = "長沙市天心區(qū)" }
};
//寫入CSV文件數(shù)據(jù)
using var writer = new StreamWriter(@".\StudentInfoFile.csv");
using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture);
csvWriter.WriteRecords(students);
}
讀取CSV文件數(shù)據(jù)
快速讀取上面寫入到StudentInfoFile.csv
中的數(shù)據(jù)。
static void Main(string[] args)
{
//讀取CSV文件數(shù)據(jù)
using var reader = new StreamReader(@".\StudentInfoFile.csv");
using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);
var getStudentInfos = csvReader.GetRecords<StudentInfo>().ToList();
}
項(xiàng)目源碼地址
更多項(xiàng)目實(shí)用功能和特性歡迎前往項(xiàng)目開源地址查看👀,別忘了給項(xiàng)目一個(gè)Star支持💖。
參考文章
該文章在 2024/7/24 23:57:25 編輯過