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.hqwc.cn/news/441426.html

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

相关文章

【RuoYi-Vue-Plus学习】项目初始化时将sql导入数据库出现Finished with error解决方法之一

将sql导入数据库出现Finished with error&#xff0c;文末是最终解决方法。 问题描述&#xff1a;sql导入出现Finished with error 解决方法探索过程&#xff1a; 1&#xff09;参考链接2和3&#xff0c;在mysql的bin目录下输入以下指令连接数据库 mysql -h localhost -u ro…

PythonSSTI漏洞

一&#xff0c;python内置PYC反编译&#xff1a; pyc文件&#xff0c;就是python的代码生成的字节码文件&#xff0c;有些类似于Java中的.class文件&#xff0c;pyc文件可以经过本地python解释器进行运行&#xff0c;从而实现跨平台。 也就是说我们得到了.pyc文件&#xff0c;就…

监测Tomcat项目宕机重启脚本(Linux)

1.准备好写好的脚本 #!/bin/sh # 获取tomcat的PID TOMCAT_PID$(ps -ef | grep tomcat | grep -v tomcatMonitor |grep -v grep | awk {print $2}) # tomcat的启动文件位置 START_TOMCAT/mnt/tomcat/bin/startup.sh # 需要监测的一个GET请求地址 MONITOR_URLhttp://localhost:…

移动端基础:rem适配布局

rem单位 rem是相对单位&#xff0c;类似于em 但rem的基准是相对于HTML元素的字体大小 rem的优点是可以通过修改HTML文字大小改变页面元素大小&#xff0c;做到整体控制 媒体查询 使用media查询&#xff0c;可以针对不同的媒体类型定义不同的样式 可以针对不同的屏幕尺寸设…

Unity_Timeline使用说明

Unity_Timeline使用说明 首先要找到工具吧&#xff1f;Unity2023.1.19f1c1打开如下&#xff1a; &#xff08;团结引擎没找见哪儿打开&#xff0c;可能是引擎问题吧&#xff1f;有知道的同学可以告诉我在哪儿打开&#xff09; Timelime使用流程&#xff1a; 打开之后会提示您…

android文本显示

目录 一.设置文本的内容 方法一 方法二 二.设置文本的大小 三.设置文本的颜色 创建新的模块 一.设置文本的内容 方法一 方法二 二.设置文本的大小 用快捷方式创建activity 换成线性布局 sp单位的会更具系统字体变大则变大 三.设置文本的颜色 八位十六进制 0xff00ff00 …

深度学习(9)--pydot库和graphviz库安装流程详解

目录 一.pydot库安装 二.graphviz库安装 一.pydot库安装 pydot的安装可直接在编译器安装相关包&#xff0c;以PyCharm举例&#xff1a; 如果搜索可用软件包显示为空&#xff0c;记得在此处把使用Conda软件包管理器”点亮 二.graphviz库安装 点击链接下载安装包graphviz-2.38…

【遥感专题系列】遥感影像信息提取之——人工目视解译

​遥感影像通过亮度值或像元值的高低差异&#xff08;反映地物的光谱信息&#xff09;及空间变化&#xff08;反映地物的空间信息&#xff09;来表示不同地物的差异&#xff0c;这是区分不同影像地物的物理基础。 ​人工解译是目前国内使用最多的一种影像提取方法&#xff0c;如…

医院安全(不良)事件报告系统源码,不良事件处理的全过程管理,实现11大类不良事件类型的报告上报、流转审批、跟踪改进及统计分析功能。

医院安全&#xff08;不良&#xff09;事件报告系统源码&#xff0c;不良事件上报系统源码&#xff0c;PHP源码 医院安全&#xff08;不良&#xff09;事件报告系统提供11大类不良事件的上报、事件审核处理、时间按分析、事件跟踪与持续改进&#xff0c;事件提醒、权限控制、外…

Walrus 实用教程|Walrus + Gitlab,打通CI/CD 自动化交付!

Walrus file 是 Walrus 0.5 版本推出的新功能&#xff0c;用户可以通过一个非常简洁的 YAML 描述应用或基础设施资源的部署配置&#xff0c;然后通过 Walrus CLI 执行 walrus apply或在 Walrus UI 上进行import&#xff0c;将 Walrus file 提交给 Walrus server&#xff0c;由 …

C++---动态内存分配 new delete

在C中&#xff0c;new和delete 是用于动态内存分配和释放的关键字。 一.利用new创建内存&#x1f357; new是在堆区申请一块连续的内存空间,如果申请成功&#xff0c;则返回内存指针&#xff1b;如果申请失败&#xff0c;则返回NULL;new申请内存空间的过程&#xff0c;通常称为…

回归预测 | Matlab实现CPO-SVR冠豪猪优化支持向量机的数据多输入单输出回归预测

回归预测 | Matlab实现CPO-SVR冠豪猪优化支持向量机的数据多输入单输出回归预测 目录 回归预测 | Matlab实现CPO-SVR冠豪猪优化支持向量机的数据多输入单输出回归预测预测效果基本描述程序设计参考资料 预测效果 基本描述 1.Matlab实现CPO-SVR冠豪猪优化支持向量机的数据多输入…