前言
CSV 文件以純文本形式存儲表格數(shù)據(jù),每行代表一條記錄,各字段之間通常以逗號作為分隔符。但在實(shí)際應(yīng)用中,也可能使用分號、制表符等其他字符作為分隔符。它被廣泛應(yīng)用于數(shù)據(jù)存儲和交換。在軟件開發(fā)中,使用 CSV 文件是常見任務(wù)。本文將介紹 FG.CsvParser 的使用方法。
FG.CsvParser
1、概述
FG.CsvParser 是 .NET 三方庫,它可以運(yùn)行在 .NET Core 和 .NET Framework 中, 它旨在使讀取、寫入和查詢 CSV 文件變得簡單高效。憑借其靈活的 API 和廣泛的配置選項(xiàng),F(xiàn)G.CsvParser 也是處理CSV文件不錯(cuò)的類庫。
// github 地址https://github.com/fermanquliyev/FG.CsvParser
2、特征
3、使用要求
在C#中使用 FG.CsvParser 庫讀取和解析CSV文件,首先需要安裝 FG.CsvParser 庫。我們通過 NuGet 包管理器來安裝或通過指令方式安裝。
PM> Install-Package FG.CsvParser// .NET 命令行控制臺> dotnet add package FG.CsvParser
安裝完成后,我們就可以引入FG.CsvHelper 命名空間,后續(xù)根據(jù)提供的API進(jìn)行讀寫文件。
4、配置信息
FG.CsvHelper 的配置非常靈活,可以通過CsvParserConfiguration類進(jìn)行各種設(shè)置(如默認(rèn)分隔符、默認(rèn)行尾和格式等)。
var configuration = new CsvParserConfiguration{ HasHeader = true, // 指定字段分隔符 Delimitter = ';', // 換行 RowSplitter = "\r\n", // 指定編碼格式 Encoding = Encoding.UTF8,};
示例了解
1、Csv 文件內(nèi)容
ID,Name,Barcode,Category,Description10001,Apple,A202502150001,fruit,紅富士蘋果10002,Grape,G202502152003,fruit,陽光葡萄
2、創(chuàng)建實(shí)例
使用默認(rèn)設(shè)置創(chuàng)建實(shí)例,打開CSV文件。
string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "product.csv");var parser = CsvParser.OpenFile(csvPath);
使用自定義配置創(chuàng)建實(shí)例,打開CSV文件。string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "product.csv");var parser = CsvParser.OpenFile(csvPath,hasHeader: true);
string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "product.csv");var configuration = new CsvParserConfiguration{ HasHeader = true, Delimitter = ',', RowSplitter = "\r\n", Encoding = Encoding.UTF8};var parser = CsvParser.OpenFile(csvPath,configuration);
3、讀取內(nèi)容
定義一個(gè)Product類。
public class Product{ [CsvColumn("ID")] public int Id { get; set; } public string Name { get; set; } public string Barcode { get; set; } public string Category { get; set; } public string Description { get; set; }}
將 CSV 內(nèi)容轉(zhuǎn)換為 JSON 格式內(nèi)容。
static async Task Main(string[] args){ var configuration = new CsvParserConfiguration { HasHeader = true, // 指定字段分隔符 Delimitter = ';', // 換行 RowSplitter = "\r\n", // 指定編碼格式 Encoding = Encoding.UTF8, }; string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "product.csv"); var parser = CsvParser.OpenFile(csvPath, configuration); string? jsonContent = await parser.ReadAsJson(); Console.WriteLine(jsonContent); Console.Read();}
將 CSV 內(nèi)容轉(zhuǎn)換為對象列表。
static async Task Main(string[] args){ string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "product.csv"); var parser = CsvParser.OpenFile(csvPath, hasHeader: true); List<Product> productList = await parser.ReadAs<Product>(); foreach (var data in productList) { Console.WriteLine($"ID:{data.Id}, Name:{data.Name}, Barcode:{data.Barcode},Category:{data.Category},Description:{data.Description}"); } Console.Read();}
4、寫入內(nèi)容
通過將字符串內(nèi)容寫寫入文件。
static async Task Main(string[] args){ string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "product.csv"); var parser = CsvParser.OpenFile(csvPath, hasHeader: true); string csvContent = "5001,Snakehead,F2025021550001,Fish,黑魚\r\n"; await parser.WriteAsync(csvContent,append:false); Console.Read();}
使用對象列表,并將其寫入文件。
static async Task Main(string[] args){ string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "fishProduct.csv"); var parser = CsvParser.OpenFile(csvPath, hasHeader: false); var records = new List<Product> { new Product { Id = 5001, Name = "Snakehead",Barcode="F2025021550001",Category="Fish",Description="黑魚"}, new Product { Id = 6001, Name = "Carp",Barcode="F2025021550001",Category="Fish",Description="鯉魚" }, }; await parser.WriteAsync(records, append: false); Console.Read();}
5、查詢內(nèi)容
可以使用自定義篩選條件查詢數(shù)據(jù),以僅提取所需的信息。
static async Task Main(string[] args){ string csvPath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Product.csv"); using var parser = CsvParser.OpenFile(csvPath, new CsvParserConfiguration { HasHeader = true, Delimitter = ',', RowSplitter = "\r\n", Encoding = Encoding.UTF8 }); await foreach (Product item in parser.Query<Product>(data => data.Name== "Apple")) { Console.WriteLine($"ID:{item.Id}, Name:{item.Name}, Barcode:{item.Barcode},Category:{item.Category},Description:{item.Description}"); } Console.Read();}
小結(jié)
FG.CsvParser 通過提供干凈直觀的 API 簡化了 CSV 文件的使用,提供了高效且靈活性的數(shù)據(jù)的方法。
閱讀原文:原文鏈接
該文章在 2025/2/17 12:28:07 編輯過