一、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)
{
}文章来源:https://www.toymoban.com/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>();
}
}文章来源地址https://www.toymoban.com/news/detail-508169.html
到了这里,关于C#使用CsvHelper 实现csv文件导入导出功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!