使用 WeihanLi.Npoi 操作 CSV
使用 WeihanLi.Npoi 操作 CSV
Intro#
最近发现 csv 文件在很多情况下都在使用,而且经过大致了解,csv 格式简单,相比 excel 文件要小很多,读取也很是方便,而且也很通用,微软的 ml.net 的示例项目 用来训练模型的数据也是使用的 csv 来保存的,最近又发现使用 jmeter 来测试网站的性能,也可以用 csv 来参数化请求,csv 文件操作的重要性由此可见。
此前做了一个 NPOI 的扩展 WeihanLi.Npoi,支持.net45 以及 .netstandard2.0及以上,主要是对 excel 文件的操作,于是打算再增加一些对csv的操作。
csv 操作API#
/// <summary>
/// save to csv file
/// </summary>
public static int ToCsvFile(this DataTable dt, string filePath);
public static int ToCsvFile(this DataTable dataTable, string filePath, bool includeHeader);
/// <summary>
/// to csv bytes
/// </summary>
public static byte[] ToCsvBytes(this DataTable dt);
public static byte[] ToCsvBytes(this DataTable dataTable, bool includeHeader);
/// <summary>
/// convert csv file data to dataTable
/// </summary>
/// <param name="filePath">csv file path</param>
public static DataTable ToDataTable(string filePath);
/// <summary>
/// convert csv file data to entity list
/// </summary>
/// <param name="filePath">csv file path</param>
public static List<TEntity> ToEntityList<TEntity>(string filePath) where TEntity : new();
/// <summary>
/// save to csv file
/// </summary>
public static int ToCsvFile<TEntity>(this IEnumerable<TEntity> entities, string filePath);
public static int ToCsvFile<TEntity>(this IEnumerable<TEntity> entities, string filePath, bool includeHeader);
/// <summary>
/// to csv bytes
/// </summary>
public static byte[] ToCsvBytes<TEntity>(this IEnumerable<TEntity> entities) => ToCsvBytes(entities, true);
public static byte[] ToCsvBytes<TEntity>(this IEnumerable<TEntity> entities, bool includeHeader);
通过上面的方法,即可方便的将一个 IEnumerable 对象或者是DataTable 导出为 csv 文件或者或者 csv 文件的字节数组,也可将 csv 文件转换为 DataTable 或者 List 对象。
并且我于昨天优化了 csv 转成 list 对象的操作,并且支持了简单类型(比如int/long等 )的直接导出
Sample#
var entities = new List<TestEntity>()
{
new TestEntity()
{
PKID = 1,
SettingId = Guid.NewGuid(),
SettingName = "Setting1",
SettingValue = "Value1"
},
new TestEntity()
{
PKID=2,
SettingId = Guid.NewGuid(),
SettingName = "Setting2",
SettingValue = "Value2"
},
};
var csvFilePath = $@"{Environment.GetEnvironmentVariable("USERPROFILE")}\Desktop\temp\test\test.csv";
entities.ToCsvFile(csvFilePath);
var entities1 = CsvHelper.ToEntityList<TestEntity>(csvFilePath);
entities.ToExcelFile(csvFilePath.Replace(".csv", ".xlsx"));
var vals = new[] { 1, 2, 3, 5, 4 };
vals.ToCsvFile(csvFilePath);
var numList = CsvHelper.ToEntityList<int>(csvFilePath);
Console.WriteLine(numList.StringJoin(","));
更多详情可参考示例:https://github.com/WeihanLi/WeihanLi.Npoi/blob/dev/samples/DotNetCoreSample/Program.cs
More#
导入导出的时候如果根据需要配置要导出的属性以及顺序,和之前导出 Excel 相似,需要配置一下 ,目前和 Excel 导入导出共享配置,配置方式支持 Attribute 或者 FluentAPI 两种方式(不支持Excel的一些配置如Author,title、subject以及sheet等信息),示例如下:
// Attribute config
public class TestEntity
{
public string Username { get; set; }
[Column(IsIgnored = true)]
public string PasswordHash { get; set; }
public decimal Amount { get; set; } = 1000M;
public string WechatOpenId { get; set; }
public bool IsActive { get; set; }
}
// Fluent API
var setting = ExcelHelper.SettingFor<TestEntity>();
// ExcelSetting
setting.HasAuthor("WeihanLi")
.HasTitle("WeihanLi.Npoi test")
.HasDescription("")
.HasSubject("");
setting.Property(_ => _.SettingId)
.HasColumnIndex(0);
setting.Property(_ => _.SettingName)
.HasColumnIndex(1);
setting.Property(_ => _.DisplayName)
.HasColumnIndex(2);
setting.Property(_ => _.SettingValue)
.HasColumnIndex(3);
setting.Property(_ => _.CreatedTime)
.HasColumnIndex(5);
setting.Property(_ => _.CreatedBy)
.HasColumnIndex(4);
setting.Property(_ => _.UpdatedBy).Ignored();
setting.Property(_ => _.UpdatedTime).Ignored();
setting.Property(_ => _.PKID).Ignored();
更多配置详情参考:https://github.com/WeihanLi/WeihanLi.Npoi#define-custom-mapping-and-settings
End#
如果有 csv 文件操作的需求,可以尝试使用它,如果不能满足你的需求欢迎来给我提 issue
作者:weihanli
出处:https://www.cnblogs.com/weihanli/p/operate-csv-files-with-weihanli_npoi.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?