【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 助手类:

  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using System.Text;
  5. using System.Web;
  6. using NPOI.HPSF;
  7. using NPOI.HSSF.UserModel;
  8. using NPOI.SS.UserModel;
  9. using System.Collections.Generic;
  10. using System.Collections;
  11. namespace Weilog.Core.Document.Excel
  12. {
  13. /// <summary>
  14. /// Excel 助手类。
  15. /// </summary>
  16. public class ExcelHelper
  17. {
  18.  
  19. private void InitializeWorkbook(HSSFWorkbook hssfworkbook, string headerText)
  20. {
  21. hssfworkbook = new HSSFWorkbook();
  22.  
  23. //创建一个文档摘要信息实体。
  24. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  25. dsi.Company = "Weilog Team"; //公司名称
  26. hssfworkbook.DocumentSummaryInformation = dsi;
  27.  
  28. //创建一个摘要信息实体。
  29. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  30. si.Subject = "Weilog 系统生成";
  31. si.Author = "Weilog 系统";
  32. si.Title = headerText;
  33. si.Subject = headerText;
  34. si.CreateDateTime = DateTime.Now;
  35. hssfworkbook.SummaryInformation = si;
  36.  
  37. }
  38.  
  39. private static MemoryStream WriteToStream(HSSFWorkbook hssfworkbook)
  40. {
  41. //Write the stream data of workbook to the root directory
  42. MemoryStream file = new MemoryStream();
  43. hssfworkbook.Write(file);
  44. return file;
  45. }
  46. //Export(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle)
  47. /// <summary>
  48. /// 向客户端输出文件。
  49. /// </summary>
  50. /// <param name="table">数据表。</param>
  51. /// <param name="headerText">头部文本。</param>
  52. /// <param name="sheetName"></param>
  53. /// <param name="columnName">数据列名称。</param>
  54. /// <param name="columnTitle">表标题。</param>
  55. /// <param name="fileName">文件名称。</param>
  56. public static void Write(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle, string fileName)
  57. {
  58. HttpContext context = HttpContext.Current;
  59. context.Response.ContentType = "application/vnd.ms-excel";
  60. context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",HttpUtility.UrlEncode(fileName, Encoding.UTF8)));
  61. context.Response.Clear();
  62. HSSFWorkbook hssfworkbook = GenerateData(table, headerText, sheetName, columnName, columnTitle);
  63. context.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer());
  64. context.Response.End();
  65. }
  66. /// <summary>
  67. ///
  68. /// </summary>
  69. /// <param name="table"></param>
  70. /// <param name="headerText"></param>
  71. /// <param name="sheetName"></param>
  72. /// <param name="columnName"></param>
  73. /// <param name="columnTitle"></param>
  74. /// <returns></returns>
  75. public static HSSFWorkbook GenerateData(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle)
  76. {
  77. HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  78. ISheet sheet = hssfworkbook.CreateSheet(sheetName);
  79.  
  80. #region 设置文件属性信息
  81.  
  82. //创建一个文档摘要信息实体。
  83. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  84. dsi.Company = "Weilog Team"; //公司名称
  85. hssfworkbook.DocumentSummaryInformation = dsi;
  86.  
  87. //创建一个摘要信息实体。
  88. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  89. si.Subject = "本文档由 Weilog 系统生成";
  90. si.Author = " Weilog 系统";
  91. si.Title = headerText;
  92. si.Subject = headerText;
  93. si.CreateDateTime = DateTime.Now;
  94. hssfworkbook.SummaryInformation = si;
  95.  
  96. #endregion
  97.  
  98. ICellStyle dateStyle = hssfworkbook.CreateCellStyle();
  99. IDataFormat format = hssfworkbook.CreateDataFormat();
  100. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  101.  
  102. #region 取得列宽
  103.  
  104. int[] colWidth = new int[columnName.Length];
  105. for (int i = 0; i < columnName.Length; i++)
  106. {
  107. colWidth[i] = Encoding.GetEncoding(936).GetBytes(columnTitle[i]).Length;
  108. }
  109. for (int i = 0; i < table.Rows.Count; i++)
  110. {
  111. for (int j = 0; j < columnName.Length; j++)
  112. {
  113. int intTemp = Encoding.GetEncoding(936).GetBytes(table.Rows[i][columnName[j]].ToString()).Length;
  114. if (intTemp > colWidth[j])
  115. {
  116. colWidth[j] = intTemp;
  117. }
  118. }
  119. }
  120.  
  121. #endregion
  122.  
  123. int rowIndex = 0;
  124. foreach (DataRow row in table.Rows)
  125. {
  126. #region 新建表,填充表头,填充列头,样式
  127. if (rowIndex == 65535 || rowIndex == 0)
  128. {
  129. if (rowIndex != 0)
  130. {
  131. sheet = hssfworkbook.CreateSheet(sheetName + ((int)rowIndex / 65535).ToString());
  132. }
  133.  
  134. #region 表头及样式
  135. //if (!string.IsNullOrEmpty(headerText))
  136. {
  137. IRow headerRow = sheet.CreateRow(0);
  138. headerRow.HeightInPoints = 25;
  139. headerRow.CreateCell(0).SetCellValue(headerText);
  140.  
  141. ICellStyle headStyle = hssfworkbook.CreateCellStyle();
  142. headStyle.Alignment = HorizontalAlignment.CENTER;
  143. IFont font = hssfworkbook.CreateFont();
  144. font.FontHeightInPoints = 20;
  145. font.Boldweight = 700;
  146. headStyle.SetFont(font);
  147.  
  148. headerRow.GetCell(0).CellStyle = headStyle;
  149. //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
  150. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
  151. }
  152. #endregion
  153.  
  154. #region 列头及样式
  155. {
  156. //HSSFRow headerRow = sheet.CreateRow(1);
  157. IRow headerRow;
  158. //if (!string.IsNullOrEmpty(headerText))
  159. //{
  160. // headerRow = sheet.CreateRow(0);
  161. //}
  162. //else
  163. //{
  164. headerRow = sheet.CreateRow(1);
  165. //}
  166. ICellStyle headStyle = hssfworkbook.CreateCellStyle();
  167. headStyle.Alignment = HorizontalAlignment.CENTER;
  168. IFont font = hssfworkbook.CreateFont();
  169. font.FontHeightInPoints = 10;
  170. font.Boldweight = 700;
  171. headStyle.SetFont(font);
  172.  
  173. for (int i = 0; i < columnName.Length; i++)
  174. {
  175. headerRow.CreateCell(i).SetCellValue(columnTitle[i]);
  176. headerRow.GetCell(i).CellStyle = headStyle;
  177. //设置列宽
  178. if ((colWidth[i] + 1) * 256 > 30000)
  179. {
  180. sheet.SetColumnWidth(i, 10000);
  181. }
  182. else
  183. {
  184. sheet.SetColumnWidth(i, (colWidth[i] + 1) * 256);
  185. }
  186. }
  187. /*
  188. foreach (DataColumn column in dtSource.Columns)
  189. {
  190. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  191. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  192.  
  193. //设置列宽
  194. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  195. }
  196. * */
  197. }
  198. #endregion
  199. //if (!string.IsNullOrEmpty(headerText))
  200. //{
  201. // rowIndex = 1;
  202. //}
  203. //else
  204. //{
  205. rowIndex = 2;
  206. //}
  207.  
  208. }
  209. #endregion
  210.  
  211. #region 填充数据
  212.  
  213. IRow dataRow = sheet.CreateRow(rowIndex);
  214. for (int i = 0; i < columnName.Length; i++)
  215. {
  216. ICell newCell = dataRow.CreateCell(i);
  217.  
  218. string drValue = row[columnName[i]].ToString();
  219.  
  220. switch (table.Columns[columnName[i]].DataType.ToString())
  221. {
  222. case "System.String"://字符串类型
  223. if (drValue.ToUpper() == "TRUE")
  224. newCell.SetCellValue("是");
  225. else if (drValue.ToUpper() == "FALSE")
  226. newCell.SetCellValue("否");
  227. newCell.SetCellValue(drValue);
  228. break;
  229. case "System.DateTime"://日期类型
  230. DateTime dateV;
  231. DateTime.TryParse(drValue, out dateV);
  232. newCell.SetCellValue(dateV);
  233.  
  234. newCell.CellStyle = dateStyle;//格式化显示
  235. break;
  236. case "System.Boolean"://布尔型
  237. bool boolV = false;
  238. bool.TryParse(drValue, out boolV);
  239. if (boolV)
  240. newCell.SetCellValue("是");
  241. else
  242. newCell.SetCellValue("否");
  243. break;
  244. case "System.Int16"://整型
  245. case "System.Int32":
  246. case "System.Int64":
  247. case "System.Byte":
  248. int intV = 0;
  249. int.TryParse(drValue, out intV);
  250. newCell.SetCellValue(intV);
  251. break;
  252. case "System.Decimal"://浮点型
  253. case "System.Double":
  254. double doubV = 0;
  255. double.TryParse(drValue, out doubV);
  256. newCell.SetCellValue(doubV);
  257. break;
  258. case "System.DBNull"://空值处理
  259. newCell.SetCellValue("");
  260. break;
  261. default:
  262. newCell.SetCellValue("");
  263. break;
  264. }
  265.  
  266. }
  267.  
  268. #endregion
  269.  
  270. rowIndex++;
  271. }
  272.  
  273. return hssfworkbook;
  274. }
  275. }
  276. }

使用的过程中需要将实体对象集合转换成 DataTable

使用方法:

  1. #region 将指定的集合转换成数据表...
  2.  
  3. /// <summary>
  4. /// 将指定的集合转换成DataTable。
  5. /// </summary>
  6. /// <param name="list">将指定的集合。</param>
  7. /// <returns>返回转换后的DataTable。</returns>
  8. public static DataTable ListToDataTable(IList list)
  9. {
  10. DataTable table = new DataTable();
  11. if (list.Count > 0)
  12. {
  13. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  14. foreach (PropertyInfo pi in propertys)
  15. {
  16. Type pt = pi.PropertyType;
  17. if ((pt.IsGenericType) && (pt.GetGenericTypeDefinition() == typeof(Nullable<>)))
  18. {
  19. pt = pt.GetGenericArguments()[0];
  20. }
  21. table.Columns.Add(new DataColumn(pi.Name, pt));
  22. }
  23.  
  24. for (int i = 0; i < list.Count; i++)
  25. {
  26. ArrayList tempList = new ArrayList();
  27. foreach (PropertyInfo pi in propertys)
  28. {
  29. object obj = pi.GetValue(list[i], null);
  30. tempList.Add(obj);
  31. }
  32. object[] array = tempList.ToArray();
  33. table.LoadDataRow(array, true);
  34. }
  35. }
  36. return table;
  37. }
  38.  
  39. #endregion
  40.  
  41. #region 导出数据...
  42.  
  43. private void ExportData(List<ProductInfo> productList)
  44. {
  45. var exportDataList =
  46. (from productInfo in ProductList
  47. new
  48. {
  49. Code = productInfo.Code,
  50. Name = productInfo.Name,
  51. DeptName = productInfo.DeptName,
  52. ProjectName = productInfo.ProjectName,
  53. CategoryName = productInfo.CategoryName,
  54. Intro = productInfo.Intro,
  55. Level = productInfo.Level,
  56. Objective = productInfo.Objective
  57. }).ToList();
  58.  
  59. DataTable table = ListToDataTable(exportDataList);
  60. string[] strFields = { "Code", "Name", "DeptName", "ProjectName", "CategoryName", "Intro", "Level", "Objective" };
  61. string[] strFieldsName = { "编码", "名称", "所属部门", "所属项目", "分类", "简介", "等级", "目标" };
  62. ExcelHelper.Write(table, "产品表", "产品表", strFields, strFieldsName, "产品表.xls");
  63. }
  64.  
  65. #endregion

使用 NPOI 导出 Excel 文件的更多相关文章

  1. 使用NPOI导出Excel文件

    使用NPOI导出Excel文件,本实例使用了ASP.NET MVC. 1.使用NPOI导出Excel文件 实例:导出商品列表. 要求:1.通过NPOI导出导出商品列表信息: 2.使用Excel函数计算 ...

  2. 关于NPOI导出excel文件(xls和xlsx两种格式)提示格式不符的问题

    这两天在做导出excel文件的时候遇到这个问题 本来我导出的格式是xlsx格式的,但是下载得到的文件格式变成了xls, 一开始以为是返回的contenttype设置错了 return File(ms, ...

  3. 基于Vue + axios + WebApi + NPOI导出Excel文件

    一.前言 项目中前端采用的Element UI 框架, 远程数据请求,使用的是axios,后端接口框架采用的asp.net webapi,数据导出成Excel采用NPOI组件.其业务场景,主要是列表页 ...

  4. C# 未安装Office环境下使用NPOI导出Excel文件

    1.NuGet直接安装NPOI程序包: 2. using NPOI.XSSF.UserModel; 3.导出Excel代码: private void TsbExport2ExcelClick(obj ...

  5. asp.net Mvc 使用NPOI导出Excel文件

    1.新建MVC项目,新建控制器.视图 添加控制器: 添加视图(将使用布局页前面的复选框里的勾勾去掉) 2.在Models里新建一个类 public class Shop { /// <summa ...

  6. C# DataGridview用NPOI导出Excel文件

    导出excel我用的是nuget 的NPOI,直接在项目中添加的,引用到项目中,下面是截图: 下面我把ExcelHelper贴出来 public static class ExcelHelper { ...

  7. NPOI导出Excel文件,对单元格的一些设置

    HSSFWorkbook book = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); ISheet sheet = book.Cr ...

  8. 使用NPOI或EPPlus来导出Excel文件实例,可在Excel文件加密

    使用NPOI.dll组件来导出Excel文件,并设置样式,Nuget引用即可. packages\NPOI.2.1.3.1\lib\net20\NPOI.dll #region Excel prote ...

  9. C#,使用NPOI,导出excel文件

    /// <summary> /// 导出excel文件 /// </summary> /// <param name="dt">Table表数据 ...

随机推荐

  1. neutron-删除负载均衡器

    neutron-删除负载均衡器 在清除垃圾数据的时候,删除负载均衡器,总是有很多依赖.写了一个脚本,连同依赖资源一起删除 #!/bin/bash delete(){ local id id=$1 lo ...

  2. vue实战记录(二)- vue实现购物车功能之创建vue实例

    vue实战,一步步实现vue购物车功能的过程记录,课程与素材来自慕课网,自己搭建了express本地服务器来请求数据 作者:狐狸家的鱼 本文链接:vue实战-实现购物车功能(二) GitHub:sue ...

  3. expansion pattern ‘Frame&’ contains no argument packs

    camera/CameraImpl.h::: error: expansion pattern ‘Frame&’ contains no argument packs void read_fr ...

  4. 编写高质量的Python代码系列(一)之用Pythonic方式来思考

    Python开发者用Pythonic这个形容词来描述具有特定风格的代码.这种风格是大家在使用Python语言进行编程并相互协作的过程中逐渐形成的习惯.那么,如何以改风格完成常见的Python编程工作呢 ...

  5. Entity Framework入门教程(11)---EF6中的异步查询和异步保存

    EF6中的异步查询和异步保存 在.NET4.5中介绍了异步操作,异步操作在EF中也很有用,在EF6中我们可以使用DbContext的实例进行异步查询和异步保存. 1.异步查询 下边是一个通过L2E语法 ...

  6. 中间件方法必须返回Response对象实例(tp5.1+小程序结合时候出的问题)

    前言:在最近开发小程序通过中间件检查是否携带token时候报的一个错误 解决方法: 根据手册中需要return出去才可以不报错

  7. css长度单位学习(em,rem,px,vw,vh)

    绝对长度单位 绝对长度单位代表一个物理测量 [像素px(pixels)] 像素,为影像显示的基本单位,译自英文"pixel",pix是英语单词picture的常用简写,加上英语单词 ...

  8. [再寄小读者之数学篇](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}}$ 决定. ...

  9. word20161227客厅家电

    1.Applicances 厨房.清洁用家电 2.Electronics 电视.音箱类家电 3.White goods 七八十年代家电基本都是白色的,所以流行叫白色家电,至今沿用 4.sleek an ...

  10. Django之restframework

    启动流程:引入rest_framework APP 在restframework中,GET数据可以通过request.query_params.get(xxx)获取,post数据可以通过request ...