一、CsvHelper 庫 可通過nuget進行安裝
二、封裝導入導出方法
?public class MyCsvHelper
? ? {
? ? ? ? public static bool WriteCsv<T>(List<T> datas,string filePath= "logs/TagData/tag.csv")
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? var currentPath = Directory.GetCurrentDirectory();
? ? ? ? ? ? ? ? var path = Path.Combine(currentPath, filePath);
? ? ? ? ? ? ? ? //判斷文件是否存在
? ? ? ? ? ? ? ? if (!Directory.Exists(Path.GetDirectoryName( path)))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? Directory.CreateDirectory(Path.GetDirectoryName(path));
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? //判斷文件是否存在
? ? ? ? ? ? ? ? if (!File.Exists(path))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? var file = File.Create(path);
? ? ? ? ? ? ? ? ? ? file.Close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
? ? ? ? ? ? ? ? using (var writer = new StreamWriter(path, false, Encoding.GetEncoding("GB18030")))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? csv.WriteRecords(datas);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ??
? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? }
? ? ? ? ? ? catch(Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? }文章來源:http://www.zghlxwxcb.cn/news/detail-508169.html
? ? ? ? ? ? return false;
? ? ? ? }
? ? ? ? public static List<T> ReadCsv<T>(string filePath)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
? ? ? ? ? ? ? ? using (var reader = new StreamReader(filePath, Encoding.GetEncoding("GB18030")))
? ? ? ? ? ? ? ? using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? HeaderValidated = null,
? ? ? ? ? ? ? ? ? ? MissingFieldFound = null,
? ? ? ? ? ? ? ? ? ? PrepareHeaderForMatch = args => args.Header.ToLower()
? ? ? ? ? ? ? ? }))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? var foos = csv.GetRecords<T>().ToList();
? ? ? ? ? ? ? ? ? ? return foos.ToList();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? }
? ? ? ? ? ? return new List<T>();
? ? ? ? }
? ? }文章來源地址http://www.zghlxwxcb.cn/news/detail-508169.html
到了這里,關于C#使用CsvHelper 實現(xiàn)csv文件導入導出功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!