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 duplicates
                        var 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.mfbz.cn/a/358940.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

解剖 Python 代码,深入学习 interpret 库的功能和应用!

更多资料获取 &#x1f4da; 个人网站&#xff1a;ipengtao.com Python是一门广泛应用的编程语言&#xff0c;拥有丰富的标准库和第三方库&#xff0c;可以用于各种应用场景。在Python中&#xff0c;有一个名为interpret的库&#xff0c;它提供了一种强大的方式来处理和执行Py…

一个通过下标查找数值的面试题解法

最近看到一道面试题&#xff0c;面试官说是算法题。我粗略看了下&#xff0c;努力在其中寻找数学公式&#xff0c;但是最后发现它算是一个数据结构相关的题目&#xff0c;没有算法层面的知识。 // There is an array generated by a rule. // The first item is 1. If k is in …

Codeforces Round 918 (Div. 4) 解题报告 | 珂学家 | 偏序 + 扩展Dijkstra

前言 整体评价 属于VP&#xff0c;感觉还是能AK的&#xff0c;E是偏序题&#xff0c;F是改版的迪杰特斯拉。 A. Odd One Out 题型: 签到 t int(input())for i in range(t):a, b, c list(map(int, input().split()))if a b:print (c)elif a c:print (b)else:print (a)B. …

基于Python的全国主要城市天气数据可视化大屏系统

1 绪论 1.1 研究的目的与意义 近年来&#xff0c;气候变化引发全球范围内的关注。天气数据的采集和分析对于气候预测、生态环境保护等方面都起着至关重要的作用。同时&#xff0c;随着科技的不断发展&#xff0c;数据可视化已经成为了许多领域中不可或缺的一部分。基于此&…

防御保护 笔记整理

一、ASPF--- 针对应用层的包过滤 ASPF --- 针对应用层的包过滤 --- 用来抓取多通道协议中协商端口的关键数据包&#xff0c;之后&#xff0c;将端 口算出&#xff0c;将结果记录在sever-map表中&#xff0c;相当于开辟了一条隐形的通道。 FTP --- 文件传输协议 FTP协议是一个典…

指针进阶1

一&#xff0c;字符指针 顾名思义&#xff1a;字符指针指的是一种指针类型为字符指针 char*&#xff1b; char*可以是一个字符也可以是一个字符串&#xff0c;前者很好理解&#xff0c;让我们看看后者&#xff1b; eg&#xff1a;char*p"abcdef";//实际上是将首元…

【开源精选导航】GitHub-Chinese-Top-Charts:一榜在手,优质中文项目轻松找寻

各位热爱开源技术的朋友们&#xff0c;你们是否有过这样的困扰&#xff1a;面对浩瀚的GitHub海洋&#xff0c;想找寻那些具有高质量中文文档的优秀开源项目却无从下手&#xff1f;今天&#xff0c;我们就为大家揭晓一个宝藏般的开源项目——GitHub 中文项目集合&#xff08;访问…

如何在win系统部署Apache服务并实现无公网ip远程访问

文章目录 前言1.Apache服务安装配置1.1 进入官网下载安装包1.2 Apache服务配置 2.安装cpolar内网穿透2.1 注册cpolar账号2.2 下载cpolar客户端 3. 获取远程桌面公网地址3.1 登录cpolar web ui管理界面3.2 创建公网地址 4. 固定公网地址 前言 Apache作为全球使用较高的Web服务器…

idea项目如何上传gitee

1.先创建仓库 2.从gitee上面clone下来 3.配置一下git 4.在idea里面安装Gitee插件&#xff08;安装完插件重启一下&#xff09; 5.将项目提交到远程仓库 git->add->✔ 完后点击↗ 在码云如何获取token&#xff1f; 注&#xff1a;没有解决&#xff0c;有时间在继续研究

linux kernel 内存踩踏之KASAN(一)

一、背景 linux 内核出现内存类问题时&#xff0c;我们常用的调试工具就是kasan&#xff0c;kasan有三种模式&#xff1a; 1. Generic KASAN &#xff08;这个就是我们最常用的&#xff0c;1 debug byte indicate 8 bytes use state, 对标用户层 asan&#xff09; 2. Softwa…

滴滴举行网约车合作伙伴大会,与174家合作伙伴共商发展

近日&#xff0c;滴滴在昆明举行主题为“凝心聚力&#xff0c;共享发展”的第四届网约车合作伙伴大会&#xff0c;汽车租赁公司、司机服务公司、主机厂、金融机构等174家上下游生态链合作伙伴齐聚一堂。滴滴已连续四年举办网约车合作伙伴大会&#xff0c;邀请合作伙伴广泛参与、…

机器学习 | 掌握 K-近邻算法 的理论实现和调优技巧

目录 初识K-近邻算法 距离度量 K值选择 kd树 数据集划分 特征预处理 莺尾花种类预测(实操) 交叉验证与网格搜索 初识K-近邻算法 K-近邻算法&#xff08;K-Nearest Neighbor&#xff0c;KNN&#xff09;是一种基本的分类和回归算法。它的基本思想是通过找出与新对象最近…

万户 ezOFFICE DocumentEdit_unite.jsp SQL注入漏洞复现

0x01 产品简介 万户OA ezoffice是万户网络协同办公产品多年来一直将主要精力致力于中高端市场的一款OA协同办公软件产品,统一的基础管理平台,实现用户数据统一管理、权限统一分配、身份统一认证。统一规划门户网站群和协同办公平台,将外网信息维护、客户服务、互动交流和日…

一文速学-selenium高阶操作连接已存在浏览器

前言 不得不说selenium不仅在自动化测试作为不可或缺的工具&#xff0c;在数据获取方面也是十分好用&#xff0c;能够十分快速的见到效果&#xff0c;这都取决于selenium框架的足够的灵活性&#xff0c;甚至在一些基于web端的自动化办公都十分有效。 通过selenium连接已经存在…

[NCTF2019]Fake XML cookbook(特详解)

先试了一下弱口令&#xff0c;哈哈习惯了 查看页面源码发现xml function doLogin(){var username $("#username").val();var password $("#password").val();if(username "" || password ""){alert("Please enter the usern…

【三】【C++】类与对象(二)

类的六个默认成员函数 在C中&#xff0c;有六个默认成员函数&#xff0c;它们是编译器在需要的情况下自动生成的成员函数&#xff0c;如果你不显式地定义它们&#xff0c;编译器会自动提供默认实现。这些默认成员函数包括&#xff1a; 默认构造函数 (Default Constructor)&…

设计模式之框架源码剖析(实战+图解)

Java设计模式 1&#xff0c;概述 随着软件开发人员人数的增多&#xff0c;一些公司急需一些高端人才。作为一个高端人才&#xff0c;设计面向对象软件是必不可少的能力&#xff0c;而软件设计是需要很深的功力&#xff0c;设计模式就要求你必须掌握。 2&#xff0c;本章特色…

中国地区cetos7.9 install kubeadmin

第 1 步&#xff1a;禁用 SELinux&#xff08;可选但推荐&#xff09; 如何在 CentOS 7 上查找 SELinux 状态 sestatus另一种选择是运行以下 cat 命令&#xff1a; vi /etc/selinux/config SELINUXdisabled rebootcentos7 linux 安装k8s前下面操作的作用是&#xff1f; cat…

基于JAVA的河南软件客服系统 开源项目

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 系统管理人员2.2 业务操作人员 三、系统展示四、核心代码4.1 查询客户4.2 新增客户跟进情况4.3 查询客户历史4.4 新增服务派单4.5 新增客户服务费 五、免责说明 一、摘要 1.1 项目介绍 基于JAVAVueSpringBootMySQL的河…

day38_MySQL

今日内容 0 复习昨日 1 引言 2 数据库 3 数据库管理系统 4 MySQL 5 SQL语言 0 复习昨日 1 引言 1.1 现有的数据存储方式有哪些&#xff1f; Java程序存储数据&#xff08;变量、对象、数组、集合&#xff09;&#xff0c;数据保存在内存中&#xff0c;属于瞬时状态存储。文件&…
最新文章