使用 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.Npoi 操作 CSV的更多相关文章
- WeihanLi.Npoi 1.13.0 更新日志
WeihanLi.Npoi 1.13.0 更新日志 Intro 在 Github 上收到 Issue 收到网友反馈希望支持自动分 Sheet 导出,有兴趣的可以参考 Issue https://git ...
- WeihanLi.Npoi 导出支持自定义列内容啦
WeihanLi.Npoi 导出支持自定义列内容啦 Intro 之前也有网友给提出过希望列合并或者自定义列内容的 issue 或请求,起初因为自己做 WeihanLi.Npoi 这个扩展的最初目的是导 ...
- WeihanLi.Npoi 近期更新
WeihanLi.Npoi 近期更新 Intro 最近对我的 NPOI 扩展做了一些改变,一方面提高性能,一方面修复bug,增加一些新的功能来让它更加好用,前几天发布了 1.5.0 版本,下面来介绍一 ...
- WeihanLi.Npoi 支持 ShadowProperty 了
WeihanLi.Npoi 支持 ShadowProperty 了 Intro 在 EF 里有个 ShadowProperty (阴影属性/影子属性)的概念,你可以通过 FluentAPI 的方式来定 ...
- WeihanLi.Npoi 根据模板导出Excel
WeihanLi.Npoi 根据模板导出Excel Intro 原来的导出方式比较适用于比较简单的导出,每一条数据在一行,数据列虽然自定义程度比较高,如果要一条数据对应多行就做不到了,于是就想支持根据 ...
- WeihanLi.Npoi 1.10.0 更新日志
WeihanLi.Npoi 1.10.0 更新日志 Intro 上周有个网友希望能够导入Excel时提供一个 EndRowIndex 来自己控制结束行和根据字段过滤的,周末找时间做了一下这个 feat ...
- WeihanLi.Npoi 1.11.0/1.12.0 Release Notes
WeihanLi.Npoi 1.11.0/1.12.0 Release Notes Intro 最近 NPOI 扩展新更新了两个版本,感谢 shaka chow 的帮忙和支持,这两个 Feature ...
- NPOI操作EXCEL(四)——反射机制批量导出excel文件
前面我们已经实现了反射机制进行excel表格数据的解析,既然有上传就得有下载,我们再来写一个通用的导出方法,利用反射机制实现对系统所有数据列表的筛选结果导出excel功能. 我们来构想一下这样一个画面 ...
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
随机推荐
- [Swift]LeetCode260. 只出现一次的数字 III | Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other ele ...
- [Swift]LeetCode957. N天后的牢房 | Prison Cells After N Days
There are 8 prison cells in a row, and each cell is either occupied or vacant. Each day, whether the ...
- 安装部署jumpserver3.0
1.安装依赖包yum -y install git readline-devel automake autoconf2.下载 jumpservergit clone https://github.co ...
- 老司机教你用原生JDK 撸一个 MVC 框架!!!
其实 Spring MVC 是一个基于请求驱动的 Web 框架,并且也使用了前端控制器模式来进行设计,再根据请求映射规则分发给相应的页面控制器进行处理,具体工作原理见下图. 在这里,就不详细谈相关的原 ...
- spark System memory must be at least
运行 ScalaSpark 程序的时候出现错误: System memory * must be at least *.Please increase heap size using the --dr ...
- Event(事件)的传播与冒泡
特性说明和原理图: 标准浏览器和Ie9+浏览器都支持事件的冒泡和捕获,而IE8-浏览器只支持冒泡 标准和Ie9+浏览器用stopPropagation()或cancelBubble阻止事件传播,而ie ...
- 推荐几个Spring Cloud学习资料
研究Spring Cloud也有一段时间了,手头上有一点收集的资料,分享给小伙伴们学习. 博客 1.跟我学Spring Cloud 2.周立|Spring Cloud 3.Spring Cloud基础 ...
- 从零打卡leetcode之day 4--无重复最长字符串
题目描述: 给定一个字符串,找出不含有重复字符的最长子串的长度. 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3. ...
- leetcode — best-time-to-buy-and-sell-stock-ii
/** * Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ * * * * Say you ...
- 【Zabbix】CentOS6.9系统下部署Zabbix-agent
目录 安装Zabbix-agent 1.安装YUM源 2.安装Zabbix agent端 3.配置zabbix_agentd.conf文件 4.启动zabbix agent服务 5.zabbix图形界 ...