当前位置: 首页 > news >正文

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){}}

相关文章:

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

这里封装了3个实用类ExcelDataReaderExtensions&#xff0c;ExcelDataSetConfiguration&#xff0c;ExcelDataTableConfiguration和一个实用代码参考&#xff1a; using ExcelDataReader; using System; using System.Collections.Generic; using System.Linq; using System.T…...

axios结合ts使用,取消请求,全局统一获取数据,抛出错误信息

通常在开发时&#xff0c;后端向前端返回的数据可以如下&#xff1a; 1 使用restful api充分利用http状态码&#xff0c;然后在data中追加code字段&#xff0c;请求成功返回200,请求失败返回404,401,500等状态码&#xff0c;并且在code字段中给出详细的字符串信息2 再包一层&a…...

MongoDB:从容器使用到 Mongosh、Python/Node.js 数据操作(结构清晰万字长文)

文章目录 1. 容器与应用之间的关系介绍2. 使用 Docker 容器安装 MongoDB3. Mongosh 操作3.1 Mongosh 连接到 MongoDB3.2 基础操作与 CRUD 4. Python 操作 MongoDB5. Nodejs 操作 MongoDB5.1 Mongodb 和 Mongoose5.2 推荐在项目中使用 Mongoose 参考文献 1. 容器与应用之间的关系…...

超越传统—Clean架构打造现代Android架构指南

超越传统—Clean架构打造现代Android架构指南 1. 引言 在过去几年里&#xff0c;Android应用开发经历了巨大的变革和发展。随着移动设备的普及和用户对应用的期望不断提高&#xff0c;开发人员面临着更多的挑战和需求。传统的Android架构在应对这些挑战和需求时显得有些力不从…...

WebGL开发项目的类型

WebGL&#xff08;Web Graphics Library&#xff09;是一种用于在Web浏览器中渲染交互式3D和2D图形的JavaScript API。使用WebGL&#xff0c;可以开发各种类型的项目&#xff0c;包括但不限于以下几种&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&#xff0c;专业…...

CUDA编程- - GPU线程的理解 thread,block,grid - 学习记录

GPU线程的理解 thread,block,grid 一、从 cpu 多线程角度理解 gpu 多线程1、cpu 多线程并行加速2、gpu多线程并行加速2.1、cpu 线程与 gpu 线程的理解&#xff08;核函数&#xff09;2.1.1 、第一步&#xff1a;编写核函数2.1.2、第二步&#xff1a;调用核函数&#xff08;使用…...

yum 报错 ZLIB_1.2.3.3 not defined in file libz.so.1

这篇记录工作中发现的&#xff0c;库文件被修改导致 yum 无法正常使用的问题排查过程 问题描述 1&#xff09;执行yum 报错说python2.7.5 结构异常&#xff0c;发现/usr/bin/yum 的解释器被修改过&#xff0c;恢复成/usr/bin/python即可 2&#xff09;恢复后&#xff0c;发现…...

数字孪生智慧能源电力Web3D可视化云平台合集

前言 能源电力的经济发展是中国式现代化的强大动力&#xff0c;是经济社会发展的必要生产要素&#xff0c;电力成本变化直接关系到工业生产、交通运输、农业生产、居民生活等各个方面&#xff0c;合理、经济的能源成本能够促进社会用能服务水平提升、支撑区域产业发展&#xf…...

DataTable.Load(reader)注意事项

对于在C#中操作数据库查询&#xff0c;这样的代码很常见&#xff1a; using var cmd ExecuteCommand(sql); using var reader cmd.ExecuteReader(); DataTable dt new DataTable(); dt.Load(reader); ...一般的查询是没问题的&#xff0c;但是如果涉及主键列的查询&#xf…...

DC-DNS(域名解析服务)(23国赛真题)

2023全国职业院校技能大赛网络系统管理赛项–模块B:服务部署(WindowServer2022) 文章目录 题目配置步骤安装及配置DNS服务。创建正向区域,添加必要的域名解析记录。配置TXT记录,配置域名反向PTR。无法解析的域名统一交由IspSrv进行解析验证配置chinaskills.com正向区域配置…...

日志之Loki详细讲解

文章目录 1 Loki1.1 引言1.2 Loki工作方式1.2.1 日志解析格式1.2.2 日志搜集架构模式1.2.3 Loki部署模式 1.3 服务端部署1.3.1 AllInOne部署模式1.3.1.1 k8s部署1.3.1.2 创建configmap1.3.1.3 创建持久化存储1.3.1.4 创建应用1.3.1.5 验证部署结果 1.3.2 裸机部署 1.4 Promtail…...

Mongodb投射中的$slice,正向反向跳过要搞清楚

在投射中&#xff0c;使用$操作符和$elemMatch返回数组中第一个符合查询条件的元素。而在投射中使用$slice, 能够返回指定数量的数组元素。 定义 投射中使用$slice命令&#xff0c;指定查询结果中返回数组元素的数量。 语法 db.collection.find(<query>,{<arrayFi…...

类和对象 第六部分 继承 第一部分:继承的语法

一.继承的概念 继承是面向对象的三大特性之一 有些类与类之间存在特殊的关系&#xff0c;例如下图&#xff1a; 我们可以发现&#xff0c;下级别的成员除了拥有上一级的共性&#xff0c;还有自己的特性&#xff0c;这个时候&#xff0c;我们可以讨论利用继承的技术&#xff0c;…...

githacker安装详细教程,linux添加环境变量详细教程(见标题三)

笔者是ctf小白&#xff0c;这两天也是遇到.git泄露的题目&#xff0c;需要工具来解决问题&#xff0c;在下载和使用的过程中也是遇到很多问题&#xff0c;写此篇记录经验&#xff0c;以供学习 在本篇标题三中有详细介绍了Linux系统添加环境变量的操作教程&#xff0c;以供学习 …...

2401Idea用GradleKotlin编译Java控制台中文出乱码解决

解决方法 解决方法1 在项目 build.gradle.kts 文件中加入 tasks.withType<JavaCompile> {options.encoding "UTF-8" } tasks.withType<JavaExec> {systemProperty("file.encoding", "utf-8") }经测试, 只加 tasks.withType<…...

Day39 62不同路径 63不同路径II 343整数拆分 96不同的二叉搜索树

62 不同路径 一个机器人位于一个 m x n 网格的左上角 &#xff08;起始点在下图中标记为 “Start” &#xff09;。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角&#xff08;在下图中标记为 “Finish” &#xff09;。 问总共有多少条不同的路径&#…...

JavaScript 的 ~~ 运算和floor 的性能差异

在JavaScript中&#xff0c;~~&#xff08;双波浪号&#xff09;和Math.floor()都可以用于向下取整&#xff0c;但它们在行为和性能上有一些差异。要测试这两者之间的性能差异&#xff0c;你可以使用JavaScript的performance.now()方法来进行基准测试。 行为差异 Math.floor()…...

AtCoder Beginner Contest 338F - Negative Traveling Salesman【floyd+状态压缩dp】

原题链接&#xff1a;https://atcoder.jp/contests/abc338/tasks/abc338_f Time Limit: 6 sec / Memory Limit: 1024 MB Score: 500 points、 问题陈述 有一个有N个顶点和M条边的加权简单有向图。顶点的编号为 1 到 N&#xff0c;i/th 边的权重为 Wi​&#xff0c;从顶点 U…...

UDP/TCP协议特点

1.前置知识 定义应用层协议 1.确定客户端和服务端要传递哪些信息 2.约定传输格式 网络上传输的一般是二进制数据/字符串 结构化数据转二进制/字符串 称为序列化 反之称之为反序列化 下面就是传输层了 在TCP/IP协议中,我们以 目的端口,目的IP 源端口 源IP 协议号这样一个五…...

编程笔记 html5cssjs 059 css多列

编程笔记 html5&css&js 059 css多列 一、CSS3 多列属性二、实例小结 CSS3 可以将文本内容设计成像报纸一样的多列布局. 一、CSS3 多列属性 下表列出了所有 CSS3 的多列属性&#xff1a; 属性 描述 column-count 指定元素应该被分割的列数。 column-fill 指定如何填充…...

DYNAMIX:基于强化学习的动态批处理优化,破解分布式训练效率与精度困局

1. 项目概述与核心痛点在分布式机器学习&#xff08;DML&#xff09;的实际部署中&#xff0c;有一个参数总是让工程师们又爱又恨&#xff0c;那就是批处理大小&#xff08;Batch Size&#xff09;。它不像学习率那样有丰富的理论指导&#xff0c;也不像网络结构那样有清晰的演…...

别再为Unity视频播放发愁了!Video Player从创建到避坑,保姆级教程带你搞定

Unity视频播放全攻略&#xff1a;从基础配置到高级避坑技巧在游戏开发中&#xff0c;视频播放功能看似简单&#xff0c;却暗藏诸多玄机。无论是开场动画、过场剧情还是UI背景&#xff0c;流畅的视频体验直接影响玩家第一印象。本文将带你深入Unity Video Player的每一个细节&am…...

告别手动拼图!用Unity TileMap的Fill Box和Picker工具,5分钟搞定复杂地形

告别手动拼图&#xff01;用Unity TileMap的Fill Box和Picker工具高效构建复杂地形在2D游戏开发中&#xff0c;地形设计往往是耗时又繁琐的环节。想象一下&#xff0c;你需要手动放置数百个草地、水域或砖块瓦片来构建游戏世界&#xff0c;这不仅容易出错&#xff0c;还会消耗大…...

融合链上数据与市场情绪的以太坊Gas价格预测模型实践

1. 项目概述&#xff1a;当链上数据遇见市场情绪在以太坊生态里混迹多年的开发者或交易员&#xff0c;大概都经历过这样的深夜&#xff1a;盯着钱包里一笔迟迟无法确认的交易&#xff0c;看着Gas价格像过山车一样飙升&#xff0c;心里盘算着是咬牙追加Gas费&#xff0c;还是取消…...

棋牌网站渗透测试实战:弱口令与SQL注入组合利用

1. 为什么棋牌类网站是渗透测试的“黄金靶场”——从业务逻辑反推攻击面你有没有试过在凌晨两点&#xff0c;打开一个刚注册的棋牌平台&#xff0c;随手输了个“admin/admin123”&#xff0c;页面直接跳转到后台管理首页&#xff1f;我第一次遇到这种事时&#xff0c;手都停在键…...

ros2_control 代码架构分析

ros2_control 代码架构分析 一、整体框架 1.1 代码框架 ├── ros2_control/ # ★ 框架本体(vendored,jazzy 分支) │ ├── controller_manager/ # 核心运行时:ros2_control_node │ ├── hardware_interface/ # 硬件抽象 +…...

ChatGPT生成图表总“丑”?3步精准调优Prompt+4类D3.js/Plotly适配模板,即刻提升专业度

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;ChatGPT数据可视化建议 在利用ChatGPT辅助数据分析与可视化时&#xff0c;关键在于将模型生成的结构化洞察高效映射到视觉表达层。ChatGPT本身不直接渲染图表&#xff0c;但可精准生成符合主流库&#…...

1231546

123456...

ChatGPT生成内容同质化困局破局术:用故事化表达重构人机协作范式(仅限首批200位读者获取的叙事权重矩阵)

更多请点击&#xff1a; https://codechina.net 第一章&#xff1a;叙事权重矩阵的底层逻辑与人机协作范式跃迁 叙事权重矩阵并非传统意义上的数值张量&#xff0c;而是一种动态语义映射结构&#xff0c;它将人类叙事意图、上下文可信度、模型生成置信度及跨模态对齐信号统一编…...

对比直接使用原厂API,Taotoken在计费透明性上给我们的感受

&#x1f680; 告别海外账号与网络限制&#xff01;稳定直连全球优质大模型&#xff0c;限时半价接入中。 &#x1f449; 点击领取海量免费额度 对比直接使用原厂API&#xff0c;Taotoken在计费透明性上给我们的感受 在集成大模型能力到业务系统的过程中&#xff0c;API调用成…...