网站首页 编程语言 正文
NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。使用 NPOI 可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。
这里简单封装了一个使用NPOI导出Excel的DLL,方便项目使用。步骤如下:
1、NuGet包管理器添加对NPOI和log4net的安装引用
2、添加Excel属性信息类ExcelProperty.cs
////// 用于定义导出的excel属性 /// public class ExcelProperty { public ExcelProperty() { } ////// 文件基本属性 /// /// 公司名称 /// 作者信息 /// 创建程序信息 /// 填加xls文件备注 /// 填加xls文件标题信息 /// 填加文件主题信息 public ExcelProperty(string company, string author, string applicationName, string comments, string title, string subject) { this.Company = company; this.Author = author; this.ApplicationName = applicationName; this.Comments = comments; this.Title = title; this.Subject = subject; } ////// 公司名称 /// private string company = ""; ////// 公司名称 /// public string Company { get { return company; } set { company = value; } } ////// 作者信息 /// private string author = ""; ////// 作者信息 /// public string Author { get { return author; } set { author = value; } } ////// 创建程序信息 /// private string applicationName = ""; ////// 创建程序信息 /// public string ApplicationName { get { return applicationName; } set { applicationName = value; } } //////填加xls文件备注 /// private string comments = ""; //////填加xls文件备注 /// public string Comments { get { return comments; } set { comments = value; } } ////// 填加xls文件标题信息 /// private string title = ""; ////// 填加xls文件标题信息 /// public string Title { get { return title; } set { title = value; } } ////// 填加文件主题信息 /// private string subject = ""; ////// 填加文件主题信息 /// public string Subject { get { return subject; } set { subject = value; } } }
3、添加Excel导出类ExcelExportHelper.cs
using log4net; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Reflection; using System.Text; namespace NPOIExcelExportHelper { public class ExcelExportHelper { //委托 public delegate void ExportResult(bool res); public event ExportResult ExportResultEvent; //构造函数 public ExcelExportHelper() { } public ExcelExportHelper(ILog loghelper) { this.LogHelper = loghelper; } ////// 日志 /// private ILog LogHelper; ////// 要导出的Excel对象 /// private HSSFWorkbook workbook = null; ////// 要导出的Excel对象属性 /// private HSSFWorkbook Workbook { get { if (workbook == null) { workbook = new HSSFWorkbook(); } return workbook; } set { workbook = value; } } ////// 设置Excel文件基本属性 /// /// 属性 public void SetExcelProperty(ExcelProperty ep) { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = ep.Company;//填加xls文件公司信息 Workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = ep.Author; //填加xls文件作者信息 si.ApplicationName = ep.ApplicationName; //填加xls文件创建程序信息 si.Comments = ep.Comments; //填加xls文件备注 si.Title = ep.Title; //填加xls文件标题信息 si.Subject = ep.Subject;//填加文件主题信息 si.CreateDateTime = DateTime.Now; Workbook.SummaryInformation = si; } ////// 泛型列表List导出到Excel文件 /// /// 源List表 /// 标题信息 /// 保存路径 /// 列名 public void ExportToFile(List list, string strHeaderText, string strFileName, string[] titles = null) { try { //转换数据源 DataTable dtSource = ListToDataTable(list, titles); //开始导出 Export(dtSource, strHeaderText, strFileName); System.GC.Collect(); ExportResultEvent?.Invoke(true); } catch (Exception ex) { if (LogHelper != null) LogHelper.Error(string.Format("ExportToFile error:{0}", ex)); ExportResultEvent?.Invoke(false); } } /// /// DataTable导出到Excel文件 /// /// 源DataTable /// 标题信息 /// 保存路径 public void Export(DataTable dtSource, string strHeaderText, string strFileName) { using (MemoryStream ms = Export(dtSource, strHeaderText)) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } ////// DataTable导出到Excel的MemoryStream /// /// 源DataTable /// 标题信息 private MemoryStream Export(DataTable dtSource, string strHeaderText) { ISheet sheet = Workbook.CreateSheet(); ICellStyle dateStyle = Workbook.CreateCellStyle(); IDataFormat format = Workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽 int[] arrColWidth = new int[dtSource.Columns.Count]; foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表头,填充列头,样式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = Workbook.CreateSheet(); } #region 表头及样式 { IRow headerRow = sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); ICellStyle headStyle = Workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; IFont font = Workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headStyle; //CellRangeAddress四个参数为:起始行,结束行,起始列,结束列 sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); } #endregion #region 列头及样式 { IRow headerRow = sheet.CreateRow(1); ICellStyle headStyle = Workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; IFont font = Workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } } #endregion rowIndex = 2; } #endregion #region 填充内容 IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in dtSource.Columns) { ICell newCell = dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.DataType.ToString()) { case "System.String"://字符串类型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期类型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示 break; case "System.Boolean"://布尔型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮点型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值处理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { Workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; } } ////// 泛型列表List转换为DataTable /// ///泛型实体 /// 要转换的列表 /// 标题 ///public DataTable ListToDataTable (List list, string[] titles) { DataTable dt = new DataTable(); Type listType = typeof(T); PropertyInfo[] properties = listType.GetProperties(); //标题行 if (titles != null && properties.Length == titles.Length) { for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i]; dt.Columns.Add(new DataColumn(titles[i], property.PropertyType)); } } else { for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i]; dt.Columns.Add(new DataColumn(property.Name, property.PropertyType)); } } //内容行 foreach (T item in list) { DataRow dr = dt.NewRow(); for (int i = 0; i < dt.Columns.Count; i++) { dr[i] = properties[i].GetValue(item, null); } dt.Rows.Add(dr); } return dt; } } }
调用方法:
1、新建一项目,添加对上述DLL的引用
2、创建TestItem测试类
public class TestItem { public string Name { get; set; } public int Id { get; set; } public string Date { get; set; } public TestItem(string name, int id, string date) { Name = name; Id = id; Date = date; } }
3、调用
private void GetList() { Listlist = new List (); for (int i = 0; i < 100000; i++) { list.Add(new TestItem("姓名" + i, i, "2020-04-21")); } ExcelExportHelper exportHelper = new ExcelExportHelper(); exportHelper.ExportResultEvent += ExportHelper_ExportResultEvent; exportHelper.SetExcelProperty(new ExcelProperty("TEST", "DNA", "ExcelExport", "", "统计查询", "统计信息")); exportHelper.ExportToFile(list, "查询结果统计", @"C:\Test.xls", new string[]{ "姓名", "编号", "日期"}); } private void ExportHelper_ExportResultEvent(bool res) { Console.Write(res); }
4、结果
原文链接:https://blog.csdn.net/dnazhd/article/details/104791880
相关推荐
- 2022-04-27 前端实现滑动按钮AJAX与后端交互的示例代码_AJAX相关
- 2022-09-24 Python tkinter 列表框Listbox属性详情_python
- 2023-07-06 css flex实现div固定在浏览器右下角
- 2023-02-09 详解如何使用Python实现复制粘贴的功能_python
- 2022-12-01 Apache Doris Join 优化原理详解_Linux
- 2022-08-15 python datetime模块详解_python
- 2022-06-28 python神经网络使用Keras构建RNN训练_python
- 2022-07-25 Android自定义View原理(实战)_Android
- 最近更新
-
- window11 系统安装 yarn
- 超详细win安装深度学习环境2025年最新版(
- Linux 中运行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存储小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基础操作-- 运算符,流程控制 Flo
- 1. Int 和Integer 的区别,Jav
- spring @retryable不生效的一种
- Spring Security之认证信息的处理
- Spring Security之认证过滤器
- Spring Security概述快速入门
- Spring Security之配置体系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置权
- redisson分布式锁中waittime的设
- maven:解决release错误:Artif
- restTemplate使用总结
- Spring Security之安全异常处理
- MybatisPlus优雅实现加密?
- Spring ioc容器与Bean的生命周期。
- 【探索SpringCloud】服务发现-Nac
- Spring Security之基于HttpR
- Redis 底层数据结构-简单动态字符串(SD
- arthas操作spring被代理目标对象命令
- Spring中的单例模式应用详解
- 聊聊消息队列,发送消息的4种方式
- bootspring第三方资源配置管理
- GIT同步修改后的远程分支