C# 一个快速读取写入操作execl的方法封装

在这里插入图片描述
在这里插入图片描述
这里封装了3个实用类ExcelDataReaderExtensions,ExcelDataSetConfiguration,ExcelDataTableConfiguration和一个实用代码参考:

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ExeclHelper
{/// <summary>/// Processing configuration options and callbacks for AsDataTable()./// </summary>public class ExcelDataTableConfiguration{/// <summary>/// Gets or sets a value indicating the prefix of generated column names./// </summary>public string EmptyColumnNamePrefix { get; set; } = "Column";/// <summary>/// Gets or sets a value indicating whether to use a row from the data as column names./// </summary>public bool UseHeaderRow { get; set; } = false;/// <summary>/// Gets or sets a callback to determine which row is the header row. Only called when UseHeaderRow = true./// </summary>public Action<IExcelDataReader> ReadHeaderRow { get; set; }/// <summary>/// Gets or sets a callback to determine whether to include the current row in the DataTable./// </summary>public Func<IExcelDataReader, bool> FilterRow { get; set; }/// <summary>/// Gets or sets a callback to determine whether to include the specific column in the DataTable. Called once per column after reading the headers./// </summary>public Func<IExcelDataReader, int, bool> FilterColumn { get; set; }}
}
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ExeclHelper
{/// <summary>/// ExcelDataReader DataSet extensions/// </summary>public static class ExcelDataReaderExtensions{/// <summary>/// Converts all sheets to a DataSet/// </summary>/// <param name="self">The IExcelDataReader instance</param>/// <param name="configuration">An optional configuration object to modify the behavior of the conversion</param>/// <returns>A dataset with all workbook contents</returns>public static DataSet AsDataSet(this IExcelDataReader self, ExcelDataSetConfiguration configuration = null){if (configuration == null){configuration = new ExcelDataSetConfiguration();}self.Reset();var tableIndex = -1;var result = new DataSet();do{tableIndex++;if (configuration.FilterSheet != null && !configuration.FilterSheet(self, tableIndex)){continue;}var tableConfiguration = configuration.ConfigureDataTable != null? configuration.ConfigureDataTable(self): null;if (tableConfiguration == null){tableConfiguration = new ExcelDataTableConfiguration();}var table = AsDataTable(self, tableConfiguration);result.Tables.Add(table);}while (self.NextResult());result.AcceptChanges();if (configuration.UseColumnDataType){FixDataTypes(result);}self.Reset();return result;}private static string GetUniqueColumnName(DataTable table, string name){var columnName = name;var i = 1;while (table.Columns[columnName] != null){columnName = string.Format("{0}_{1}", name, i);i++;}return columnName;}private static DataTable AsDataTable(IExcelDataReader self, ExcelDataTableConfiguration configuration){var result = new DataTable { TableName = self.Name };result.ExtendedProperties.Add("visiblestate", self.VisibleState);var first = true;var emptyRows = 0;var columnIndices = new List<int>();while (self.Read()){if (first){if (configuration.UseHeaderRow && configuration.ReadHeaderRow != null){configuration.ReadHeaderRow(self);}for (var i = 0; i < self.FieldCount; i++){if (configuration.FilterColumn != null && !configuration.FilterColumn(self, i)){continue;}var name = configuration.UseHeaderRow? Convert.ToString(self.GetValue(i)): null;if (string.IsNullOrEmpty(name)){name = configuration.EmptyColumnNamePrefix + i;}// if a column already exists with the name append _i to the duplicatesvar columnName = GetUniqueColumnName(result, name);var column = new DataColumn(columnName, typeof(object)) { Caption = name };result.Columns.Add(column);columnIndices.Add(i);}result.BeginLoadData();first = false;if (configuration.UseHeaderRow){continue;}}if (configuration.FilterRow != null && !configuration.FilterRow(self)){continue;}if (IsEmptyRow(self)){emptyRows++;continue;}for (var i = 0; i < emptyRows; i++){result.Rows.Add(result.NewRow());}emptyRows = 0;var row = result.NewRow();for (var i = 0; i < columnIndices.Count; i++){var columnIndex = columnIndices[i];var value = self.GetValue(columnIndex);row[i] = value;}result.Rows.Add(row);}result.EndLoadData();return result;}private static bool IsEmptyRow(IExcelDataReader reader){for (var i = 0; i < reader.FieldCount; i++){if (reader.GetValue(i) != null)return false;}return true;}private static void FixDataTypes(DataSet dataset){var tables = new List<DataTable>(dataset.Tables.Count);bool convert = false;foreach (DataTable table in dataset.Tables){if (table.Rows.Count == 0){tables.Add(table);continue;}DataTable newTable = null;for (int i = 0; i < table.Columns.Count; i++){Type type = null;foreach (DataRow row in table.Rows){if (row.IsNull(i))continue;var curType = row[i].GetType();if (curType != type){if (type == null){type = curType;}else{type = null;break;}}}if (type == null)continue;convert = true;if (newTable == null)newTable = table.Clone();newTable.Columns[i].DataType = type;}if (newTable != null){newTable.BeginLoadData();foreach (DataRow row in table.Rows){newTable.ImportRow(row);}newTable.EndLoadData();tables.Add(newTable);}else{tables.Add(table);}}if (convert){dataset.Tables.Clear();dataset.Tables.AddRange(tables.ToArray());}}}
}
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ExeclHelper
{/// <summary>/// Processing configuration options and callbacks for IExcelDataReader.AsDataSet()./// </summary>public class ExcelDataSetConfiguration{/// <summary>/// Gets or sets a value indicating whether to set the DataColumn.DataType property in a second pass./// </summary>public bool UseColumnDataType { get; set; } = true;/// <summary>/// Gets or sets a callback to obtain configuration options for a DataTable. /// </summary>public Func<IExcelDataReader, ExcelDataTableConfiguration> ConfigureDataTable { get; set; }/// <summary>/// Gets or sets a callback to determine whether to include the current sheet in the DataSet. Called once per sheet before ConfigureDataTable./// </summary>public Func<IExcelDataReader, int, bool> FilterSheet { get; set; }}
}

运用实例:

  private IList<string> GetTablenames(DataTableCollection tables){var tableList = new List<string>();foreach (var table in tables){tableList.Add(table.ToString());}return tableList;}public void ExportExcel(){try{//创建一个工作簿IWorkbook workbook = new HSSFWorkbook();//创建一个 sheet 表ISheet sheet = workbook.CreateSheet("合并数据");//创建一行IRow rowH = sheet.CreateRow(0);//创建一个单元格ICell cell = null;//创建单元格样式ICellStyle cellStyle = workbook.CreateCellStyle();//创建格式IDataFormat dataFormat = workbook.CreateDataFormat();//设置为文本格式,也可以为 text,即 dataFormat.GetFormat("text");cellStyle.DataFormat = dataFormat.GetFormat("@");//设置列名//foreach (DataColumn col in dt.Columns)//{//    //创建单元格并设置单元格内容//    rowH.CreateCell(col.Ordinal).SetCellValue(col.Caption);//    //设置单元格格式//    rowH.Cells[col.Ordinal].CellStyle = cellStyle;//}for (int i = 0; i < Headers.Count(); i++){rowH.CreateCell(i).SetCellValue(Headers[i]);rowH.Cells[i].CellStyle = cellStyle;}//写入数据for (int i = 0; i < dataModels.Count; i++){//跳过第一行,第一行为列名IRow row = sheet.CreateRow(i + 1);for (int j = 0; j < 11; j++){cell = row.CreateCell(j);if (j == 0)cell.SetCellValue(dataModels[i].title1.ToString());if (j == 1)cell.SetCellValue(dataModels[i].title2.ToString());if (j == 2)cell.SetCellValue(dataModels[i].title3.ToString());if (j == 3)cell.SetCellValue(dataModels[i].title4.ToString());if (j == 4)cell.SetCellValue(dataModels[i].title5.ToString());if (j == 5)cell.SetCellValue(dataModels[i].title6.ToString());if (j == 6)cell.SetCellValue(dataModels[i].title7.ToString());if (j == 7)cell.SetCellValue(dataModels[i].title8.ToString());if (j == 8)cell.SetCellValue(dataModels[i].title9.ToString());if (j == 9)cell.SetCellValue(dataModels[i].title10.ToString());if (j == 10)cell.SetCellValue(dataModels[i].title11.ToString());cell.CellStyle = cellStyle;}}//设置导出文件路径string path = textBox2.Text;//设置新建文件路径及名称string savePath = path + "合并" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".xls";//创建文件FileStream file = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write);//创建一个 IO 流MemoryStream ms = new MemoryStream();//写入到流workbook.Write(ms);//转换为字节数组byte[] bytes = ms.ToArray();file.Write(bytes, 0, bytes.Length);file.Flush();//还可以调用下面的方法,把流输出到浏览器下载//OutputClient(bytes);//释放资源bytes = null;ms.Close();ms.Dispose();file.Close();file.Dispose();workbook.Close();sheet = null;workbook = null;}catch (Exception ex){}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/654344.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

别再做“背锅侠”!软件测试工程师被开发吐槽,如何应对?

作为一名软件测试工程师&#xff0c;我们的角色可以算是“战场上的后勤”&#xff0c;战役的胜败和所有团队人员都息息相关。但是难免碰到战役失败后&#xff0c;很多团队互相推脱的局面&#xff0c;而测试人员就是所有团队中的弱势群体&#xff0c;自然是首当其冲的背锅侠&…

扫雷游戏(C语言)

目录 一、前言&#xff1a; 二、游戏规则&#xff1a; 三、游戏前准备 四、游戏实现 1、打印菜单 2、初始化棋盘 3、打印棋盘 4、布置雷 5、排雷 五、完整代码 一、前言&#xff1a; 用C语言完成扫雷游戏对于初学者来说&#xff0c;难度并不是很大&#xff0c;而且通…

一份轴承振动数据集摘引 - XJTU-SY2019

1.原始引用 我第一次看到这个数据集是在知乎&#xff1a; XJTU-SY数据集轴承故障诊断 - 知乎XJTU-SY数据集包含了3种工况下的15个滚动轴承的全寿命周期振动信号&#xff0c;且明确标注了每个轴承的失效部位&#xff0c;相关论文如下&#xff1a;[1]雷亚国,韩天宇,王彪,李乃鹏…

人工智能与低代码开发: 创新技术的未来

本文将探讨人工智能与低代码开发两个创新技术的结合&#xff0c;并为读者展示这种结合对未来技术发展的巨大潜力。我们将介绍人工智能和低代码开发的概念&#xff0c;并探讨它们分别在软件开发领域的作用。接着&#xff0c;我们将讨论它们如何相互影响和协作&#xff0c;以及它…

分享|2024年7款好用的电脑监控软件

电脑监控软件作为现代企业管理中不可或缺的一部分&#xff0c;能够帮助管理者们更好地管理和监控员工电脑的使用情况&#xff0c;保障企业的信息安全和机密数据的保密。在2024年&#xff0c;电脑监控软件哪些会更受欢迎&#xff1f; 1.绿虫 优势&#xff1a;具有目前市面上所…

如何写出一篇合格且优秀的硕士毕业论文

一、软件、插件推荐 谷歌浏览器、Edge浏览器&#xff08;有自动翻译成中文的小插件&#xff09; Scholarscope、EasyPubmed(浏览器插件&#xff0c;显示影响因子&#xff0c;被引用的次数&#xff0c;链接) 知云文献翻译&#xff08;文献阅读软件&#xff09; Endnote X9(插…

动态添加字段和注解,形成class类,集合对象动态创建Excel列

一.需求 动态生成Excel列&#xff0c;因为Excel列是通过类对象字段注解来添加&#xff0c;在不确定Excel列数的情况下&#xff0c;就需要动态生成列&#xff0c;对应类对象字段也需要动态生成&#xff1b; 二.ByteBuddy字节码增强动态创建类 1.依赖 <dependencies><…

DS:经典算法OJ题(1)

创作不易&#xff0c;友友们给个三连呗&#xff01;&#xff01; 本文为经典算法OJ题练习&#xff0c;大部分题型都有多种思路&#xff0c;每种思路的解法博主都试过了&#xff08;去网站那里验证&#xff09;是正确的&#xff0c;大家可以参考&#xff01;&#xff01; 一、移…

常用芯片学习——LM2596芯片

LM2596 3A降压型稳压器 使用说明 LM2596开关电压调节器是降压型电源管理单片集成电路&#xff0c;能够输出最大3A的驱动电流&#xff0c;同时具有很好的线性和负载调节特性。芯片按照输出版本可分为四种&#xff0c;分别是3.3V、5V、12V、ADJ&#xff08;可调版本&#xff09…

一文读懂Python中的映射

python中的反射功能是由以下四个内置函数提供&#xff1a;hasattr、getattr、setattr、delattr&#xff0c;改四个函数分别用于对对象内部执行&#xff1a;检查是否含有某成员、获取成员、设置成员、删除成员。 获取成员: getattr class Foo:def __init__(self, name, age):se…

【command】使用nr简化npm run命令

参考文章 添加 alias nrnpm run通过alias启动命令可以帮助我们节省运行项目输入命令的时间 $ cd ~ $ vim .bash_profile $ source ~/.bashrc

数据结构系统刷题

本文为系统刷leetcode的记录&#xff0c;会记录自己根据代码随想录刷过的leetcode&#xff0c;方便直接点开刷题&#xff0c;时常更新 时间复杂度简记为s 空间复杂度简记为k 数组 704 二分查找 一维二分查找 &#xff08;1&#xff09;[left, right] class Solution { publi…

自然语言处理发展(自然语言处理发展经历了哪些阶段)

​​​​​​​ 一、历史发展 自然语言处理的研究始于20世纪50年代初期&#xff0c;当时的主要任务是理解自然语言&#xff0c;并将其转换为机器语言。随着计算机硬件和软件的不断发展&#xff0c;NLP也得以逐步发展。在20世纪70年代&#xff0c;Chomsky提出了语法结构理论&a…

应急响应-流量分析

在应急响应中&#xff0c;有时需要用到流量分析工具&#xff0c;。当需要看到内部流量的具体情况时&#xff0c;就需要我们对网络通信进行抓包&#xff0c;并对数据包进行过滤分析&#xff0c;最常用的工具是Wireshark。 Wireshark是一个网络封包分析软件。网络封包分析软件的…

isctf---crypto

夹里夹气 可以发现是摩斯密码 得到flag easy_rsa nc连接 rsa_d nc连接 计算d 七七的欧拉 task import gmpy2 import libnum from crypto.Util.number import *flagbISCTF{*************} mbytes_to_long(flag)plibnum.generate_prime(1024) elibnum.generate_prime(51…

数据库分表分库的原则

什么是数据库分库分表 数据库分表&#xff08;Table Sharding&#xff09; 数据库分表是将一个大表按照某种规则拆分成多个小表存储在不同的物理表中的技术。通常&#xff0c;拆分规则是基于某个列的值进行拆分&#xff0c;例如根据用户ID或日期范围等进行拆分。每个小表只包…

【TensorRT】官方文档onnx序列化教程与推理教程

官方文档onnx序列化教程与推理教程 一、构建TensorRT序列化模型二、搭建阶段&#xff08;三步走&#xff09;2.1 创建网络2.2 使用ONNX解析器导入模型2.3 构建推理引擎 三、反序列化模型四、执行推理 一、构建TensorRT序列化模型 本博客主要说明的是TensorRT C API&#xff0c…

mybatis的动态标签,在实际开发中公共的字段怎么写sql

MyBatis的动态SQL是一种强大的机制&#xff0c;可以根据不同的条件生成不同的SQL语句&#xff0c;其中的动态标签包括<if>, <choose>, <when>, <otherwise>, <trim>, <where>, <set>, <foreach>等&#xff0c;使得在实际开发中…

NPDP证书:让你的职业生涯飞升!

&#x1f31f;没错&#xff01;NPDP证书正在成为产品经理们的“新宠”&#xff01;越来越多的同行们纷纷选择考取NPDP证书&#xff0c;为什么这么火爆&#xff1f;一起来探究下吧&#xff01; &#x1f680;NPDP认证&#xff1a;产品经理的国际通行证 &#x1f4cd;NPDP&#x…

Codeforces Round 921 (Div. 2) C. Did We Get Everything Covered? (思维题)

题目链接 思路: div.2的A题是本题的铺垫, A题的意思是将前k个字母循环出现m次即可, 则将前k个字母看成一个循环节。 本题则是在长为m的字符串中找循环节&#xff0c;注意循环节的意思是前k个字母出现至少一次&#xff0c; 则可知当找到一个循环节的时候&#xff0c;这个循环节…