使用 NPOI 导出 Excel 文件
【NPOI简介】
NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。
使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。
NPOI官方教程地址:http://tonyqus.sinaapp.com
googlecode:http://code.google.com/p/npoi/
codeplex:http://npoi.codeplex.com/
Excel 助手类:
- using System;
- using System.Data;
- using System.IO;
- using System.Text;
- using System.Web;
- using NPOI.HPSF;
- using NPOI.HSSF.UserModel;
- using NPOI.SS.UserModel;
- using System.Collections.Generic;
- using System.Collections;
- namespace Weilog.Core.Document.Excel
- {
- /// <summary>
- /// Excel 助手类。
- /// </summary>
- public class ExcelHelper
- {
- private void InitializeWorkbook(HSSFWorkbook hssfworkbook, string headerText)
- {
- hssfworkbook = new HSSFWorkbook();
- //创建一个文档摘要信息实体。
- DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
- dsi.Company = "Weilog Team"; //公司名称
- hssfworkbook.DocumentSummaryInformation = dsi;
- //创建一个摘要信息实体。
- SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
- si.Subject = "Weilog 系统生成";
- si.Author = "Weilog 系统";
- si.Title = headerText;
- si.Subject = headerText;
- si.CreateDateTime = DateTime.Now;
- hssfworkbook.SummaryInformation = si;
- }
- private static MemoryStream WriteToStream(HSSFWorkbook hssfworkbook)
- {
- //Write the stream data of workbook to the root directory
- MemoryStream file = new MemoryStream();
- hssfworkbook.Write(file);
- return file;
- }
- //Export(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle)
- /// <summary>
- /// 向客户端输出文件。
- /// </summary>
- /// <param name="table">数据表。</param>
- /// <param name="headerText">头部文本。</param>
- /// <param name="sheetName"></param>
- /// <param name="columnName">数据列名称。</param>
- /// <param name="columnTitle">表标题。</param>
- /// <param name="fileName">文件名称。</param>
- public static void Write(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle, string fileName)
- {
- HttpContext context = HttpContext.Current;
- context.Response.ContentType = "application/vnd.ms-excel";
- context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",HttpUtility.UrlEncode(fileName, Encoding.UTF8)));
- context.Response.Clear();
- HSSFWorkbook hssfworkbook = GenerateData(table, headerText, sheetName, columnName, columnTitle);
- context.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer());
- context.Response.End();
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="table"></param>
- /// <param name="headerText"></param>
- /// <param name="sheetName"></param>
- /// <param name="columnName"></param>
- /// <param name="columnTitle"></param>
- /// <returns></returns>
- public static HSSFWorkbook GenerateData(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle)
- {
- HSSFWorkbook hssfworkbook = new HSSFWorkbook();
- ISheet sheet = hssfworkbook.CreateSheet(sheetName);
- #region 设置文件属性信息
- //创建一个文档摘要信息实体。
- DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
- dsi.Company = "Weilog Team"; //公司名称
- hssfworkbook.DocumentSummaryInformation = dsi;
- //创建一个摘要信息实体。
- SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
- si.Subject = "本文档由 Weilog 系统生成";
- si.Author = " Weilog 系统";
- si.Title = headerText;
- si.Subject = headerText;
- si.CreateDateTime = DateTime.Now;
- hssfworkbook.SummaryInformation = si;
- #endregion
- ICellStyle dateStyle = hssfworkbook.CreateCellStyle();
- IDataFormat format = hssfworkbook.CreateDataFormat();
- dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
- #region 取得列宽
- int[] colWidth = new int[columnName.Length];
- for (int i = 0; i < columnName.Length; i++)
- {
- colWidth[i] = Encoding.GetEncoding(936).GetBytes(columnTitle[i]).Length;
- }
- for (int i = 0; i < table.Rows.Count; i++)
- {
- for (int j = 0; j < columnName.Length; j++)
- {
- int intTemp = Encoding.GetEncoding(936).GetBytes(table.Rows[i][columnName[j]].ToString()).Length;
- if (intTemp > colWidth[j])
- {
- colWidth[j] = intTemp;
- }
- }
- }
- #endregion
- int rowIndex = 0;
- foreach (DataRow row in table.Rows)
- {
- #region 新建表,填充表头,填充列头,样式
- if (rowIndex == 65535 || rowIndex == 0)
- {
- if (rowIndex != 0)
- {
- sheet = hssfworkbook.CreateSheet(sheetName + ((int)rowIndex / 65535).ToString());
- }
- #region 表头及样式
- //if (!string.IsNullOrEmpty(headerText))
- {
- IRow headerRow = sheet.CreateRow(0);
- headerRow.HeightInPoints = 25;
- headerRow.CreateCell(0).SetCellValue(headerText);
- ICellStyle headStyle = hssfworkbook.CreateCellStyle();
- headStyle.Alignment = HorizontalAlignment.CENTER;
- IFont font = hssfworkbook.CreateFont();
- font.FontHeightInPoints = 20;
- font.Boldweight = 700;
- headStyle.SetFont(font);
- headerRow.GetCell(0).CellStyle = headStyle;
- //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
- sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
- }
- #endregion
- #region 列头及样式
- {
- //HSSFRow headerRow = sheet.CreateRow(1);
- IRow headerRow;
- //if (!string.IsNullOrEmpty(headerText))
- //{
- // headerRow = sheet.CreateRow(0);
- //}
- //else
- //{
- headerRow = sheet.CreateRow(1);
- //}
- ICellStyle headStyle = hssfworkbook.CreateCellStyle();
- headStyle.Alignment = HorizontalAlignment.CENTER;
- IFont font = hssfworkbook.CreateFont();
- font.FontHeightInPoints = 10;
- font.Boldweight = 700;
- headStyle.SetFont(font);
- for (int i = 0; i < columnName.Length; i++)
- {
- headerRow.CreateCell(i).SetCellValue(columnTitle[i]);
- headerRow.GetCell(i).CellStyle = headStyle;
- //设置列宽
- if ((colWidth[i] + 1) * 256 > 30000)
- {
- sheet.SetColumnWidth(i, 10000);
- }
- else
- {
- sheet.SetColumnWidth(i, (colWidth[i] + 1) * 256);
- }
- }
- /*
- 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
- //if (!string.IsNullOrEmpty(headerText))
- //{
- // rowIndex = 1;
- //}
- //else
- //{
- rowIndex = 2;
- //}
- }
- #endregion
- #region 填充数据
- IRow dataRow = sheet.CreateRow(rowIndex);
- for (int i = 0; i < columnName.Length; i++)
- {
- ICell newCell = dataRow.CreateCell(i);
- string drValue = row[columnName[i]].ToString();
- switch (table.Columns[columnName[i]].DataType.ToString())
- {
- case "System.String"://字符串类型
- if (drValue.ToUpper() == "TRUE")
- newCell.SetCellValue("是");
- else if (drValue.ToUpper() == "FALSE")
- newCell.SetCellValue("否");
- 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);
- if (boolV)
- newCell.SetCellValue("是");
- else
- newCell.SetCellValue("否");
- 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++;
- }
- return hssfworkbook;
- }
- }
- }
使用的过程中需要将实体对象集合转换成 DataTable
使用方法:
- #region 将指定的集合转换成数据表...
- /// <summary>
- /// 将指定的集合转换成DataTable。
- /// </summary>
- /// <param name="list">将指定的集合。</param>
- /// <returns>返回转换后的DataTable。</returns>
- public static DataTable ListToDataTable(IList list)
- {
- DataTable table = new DataTable();
- if (list.Count > 0)
- {
- PropertyInfo[] propertys = list[0].GetType().GetProperties();
- foreach (PropertyInfo pi in propertys)
- {
- Type pt = pi.PropertyType;
- if ((pt.IsGenericType) && (pt.GetGenericTypeDefinition() == typeof(Nullable<>)))
- {
- pt = pt.GetGenericArguments()[0];
- }
- table.Columns.Add(new DataColumn(pi.Name, pt));
- }
- for (int i = 0; i < list.Count; i++)
- {
- ArrayList tempList = new ArrayList();
- foreach (PropertyInfo pi in propertys)
- {
- object obj = pi.GetValue(list[i], null);
- tempList.Add(obj);
- }
- object[] array = tempList.ToArray();
- table.LoadDataRow(array, true);
- }
- }
- return table;
- }
- #endregion
- #region 导出数据...
- private void ExportData(List<ProductInfo> productList)
- {
- var exportDataList =
- (from productInfo in ProductList
- new
- {
- Code = productInfo.Code,
- Name = productInfo.Name,
- DeptName = productInfo.DeptName,
- ProjectName = productInfo.ProjectName,
- CategoryName = productInfo.CategoryName,
- Intro = productInfo.Intro,
- Level = productInfo.Level,
- Objective = productInfo.Objective
- }).ToList();
- DataTable table = ListToDataTable(exportDataList);
- string[] strFields = { "Code", "Name", "DeptName", "ProjectName", "CategoryName", "Intro", "Level", "Objective" };
- string[] strFieldsName = { "编码", "名称", "所属部门", "所属项目", "分类", "简介", "等级", "目标" };
- ExcelHelper.Write(table, "产品表", "产品表", strFields, strFieldsName, "产品表.xls");
- }
- #endregion
使用 NPOI 导出 Excel 文件的更多相关文章
- 使用NPOI导出Excel文件
使用NPOI导出Excel文件,本实例使用了ASP.NET MVC. 1.使用NPOI导出Excel文件 实例:导出商品列表. 要求:1.通过NPOI导出导出商品列表信息: 2.使用Excel函数计算 ...
- 关于NPOI导出excel文件(xls和xlsx两种格式)提示格式不符的问题
这两天在做导出excel文件的时候遇到这个问题 本来我导出的格式是xlsx格式的,但是下载得到的文件格式变成了xls, 一开始以为是返回的contenttype设置错了 return File(ms, ...
- 基于Vue + axios + WebApi + NPOI导出Excel文件
一.前言 项目中前端采用的Element UI 框架, 远程数据请求,使用的是axios,后端接口框架采用的asp.net webapi,数据导出成Excel采用NPOI组件.其业务场景,主要是列表页 ...
- C# 未安装Office环境下使用NPOI导出Excel文件
1.NuGet直接安装NPOI程序包: 2. using NPOI.XSSF.UserModel; 3.导出Excel代码: private void TsbExport2ExcelClick(obj ...
- asp.net Mvc 使用NPOI导出Excel文件
1.新建MVC项目,新建控制器.视图 添加控制器: 添加视图(将使用布局页前面的复选框里的勾勾去掉) 2.在Models里新建一个类 public class Shop { /// <summa ...
- C# DataGridview用NPOI导出Excel文件
导出excel我用的是nuget 的NPOI,直接在项目中添加的,引用到项目中,下面是截图: 下面我把ExcelHelper贴出来 public static class ExcelHelper { ...
- NPOI导出Excel文件,对单元格的一些设置
HSSFWorkbook book = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); ISheet sheet = book.Cr ...
- 使用NPOI或EPPlus来导出Excel文件实例,可在Excel文件加密
使用NPOI.dll组件来导出Excel文件,并设置样式,Nuget引用即可. packages\NPOI.2.1.3.1\lib\net20\NPOI.dll #region Excel prote ...
- C#,使用NPOI,导出excel文件
/// <summary> /// 导出excel文件 /// </summary> /// <param name="dt">Table表数据 ...
随机推荐
- neutron-删除负载均衡器
neutron-删除负载均衡器 在清除垃圾数据的时候,删除负载均衡器,总是有很多依赖.写了一个脚本,连同依赖资源一起删除 #!/bin/bash delete(){ local id id=$1 lo ...
- vue实战记录(二)- vue实现购物车功能之创建vue实例
vue实战,一步步实现vue购物车功能的过程记录,课程与素材来自慕课网,自己搭建了express本地服务器来请求数据 作者:狐狸家的鱼 本文链接:vue实战-实现购物车功能(二) GitHub:sue ...
- expansion pattern ‘Frame&’ contains no argument packs
camera/CameraImpl.h::: error: expansion pattern ‘Frame&’ contains no argument packs void read_fr ...
- 编写高质量的Python代码系列(一)之用Pythonic方式来思考
Python开发者用Pythonic这个形容词来描述具有特定风格的代码.这种风格是大家在使用Python语言进行编程并相互协作的过程中逐渐形成的习惯.那么,如何以改风格完成常见的Python编程工作呢 ...
- Entity Framework入门教程(11)---EF6中的异步查询和异步保存
EF6中的异步查询和异步保存 在.NET4.5中介绍了异步操作,异步操作在EF中也很有用,在EF6中我们可以使用DbContext的实例进行异步查询和异步保存. 1.异步查询 下边是一个通过L2E语法 ...
- 中间件方法必须返回Response对象实例(tp5.1+小程序结合时候出的问题)
前言:在最近开发小程序通过中间件检查是否携带token时候报的一个错误 解决方法: 根据手册中需要return出去才可以不报错
- css长度单位学习(em,rem,px,vw,vh)
绝对长度单位 绝对长度单位代表一个物理测量 [像素px(pixels)] 像素,为影像显示的基本单位,译自英文"pixel",pix是英语单词picture的常用简写,加上英语单词 ...
- [再寄小读者之数学篇](2014-04-01 from 2103471050@qq.com 曲线积分)
求 $\int_\vGa y^2\rd s$, 其中 $\vGa$ 由 $\dps{\sedd{\ba{rl} x^2+y^2+z^2&=a^2\\ x+z&=a \ea}}$ 决定. ...
- word20161227客厅家电
1.Applicances 厨房.清洁用家电 2.Electronics 电视.音箱类家电 3.White goods 七八十年代家电基本都是白色的,所以流行叫白色家电,至今沿用 4.sleek an ...
- Django之restframework
启动流程:引入rest_framework APP 在restframework中,GET数据可以通过request.query_params.get(xxx)获取,post数据可以通过request ...