`
pcajax
  • 浏览: 2096650 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

】.NET使用NPOI组件将数据导出Excel

 
阅读更多

1、NPOI官方网站http://npoi.codeplex.com/

   可以到此网站上去下载最新的NPOI组件版本

2、NPOI在线学习教程(中文版):

    http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html

   感谢Tony Qu分享出NPOI组件的使用方法

3、.NET调用NPOI组件导入导出Excel的操作类
  此NPOI操作类的优点如下:
   (1)支持web及winform从DataTable导出到Excel; 
   (2)生成速度很快; 
   (3)准确判断数据类型,不会出现身份证转数值等问题; 
   (4)如果单页条数大于65535时会新建工作表; 
   (5)列宽自适应;

NPOI操作类
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />-->  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Web;
  5 using System.Web.Security;
  6 using System.Web.UI;
  7 using System.Web.UI.HtmlControls;
  8 using System.Web.UI.WebControls;
  9 using System.Web.UI.WebControls.WebParts;
 10 using System.IO;
 11 using System.Text;
 12 using NPOI;
 13 using NPOI.HPSF;
 14 using NPOI.HSSF;
 15 using NPOI.HSSF.UserModel;
 16 using NPOI.HSSF.Util;
 17 using NPOI.POIFS;
 18 using NPOI.Util;  
 20 namespace PMS.Common
 21 {
 22     public class NPOIHelper
 23     {
 24         /// <summary>
 25         /// DataTable导出到Excel文件
 26         /// </summary>
 27         /// <param name="dtSource">源DataTable</param>
 28         /// <param name="strHeaderText">表头文本</param>
 29         /// <param name="strFileName">保存位置</param>
 30         public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
 31         {
 32             using (MemoryStream ms = Export(dtSource, strHeaderText))
 33             {
 34                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
 35                 {
 36                     byte[] data = ms.ToArray();
 37                     fs.Write(data, 0, data.Length);
 38                     fs.Flush();
 39                 }
 40             }
 41         }
 42 
 43         /// <summary>
 44         /// DataTable导出到Excel的MemoryStream
 45         /// </summary>
 46         /// <param name="dtSource">源DataTable</param>
 47         /// <param name="strHeaderText">表头文本</param>
 48         public static MemoryStream Export(DataTable dtSource, string strHeaderText)
 49         {
 50             HSSFWorkbook workbook = new HSSFWorkbook();
 51             HSSFSheet sheet = workbook.CreateSheet();
 52 
 53             #region 右击文件 属性信息
 54             {
 55                 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
 56                 dsi.Company = "NPOI";
 57                 workbook.DocumentSummaryInformation = dsi;
 58 
 59                 SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
 60                 si.Author = "文件作者信息"//填加xls文件作者信息
 61                 si.ApplicationName = "创建程序信息"//填加xls文件创建程序信息
 62                 si.LastAuthor = "最后保存者信息"//填加xls文件最后保存者信息
 63                 si.Comments = "作者信息"//填加xls文件作者信息
 64                 si.Title = "标题信息"//填加xls文件标题信息
 65                 si.Subject = "主题信息";//填加文件主题信息
 66                 si.CreateDateTime = DateTime.Now;
 67                 workbook.SummaryInformation = si;
 68             }
 69             #endregion
 70 
 71             HSSFCellStyle dateStyle = workbook.CreateCellStyle();
 72             HSSFDataFormat format = workbook.CreateDataFormat();
 73             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
 74 
 75             //取得列宽
 76             int[] arrColWidth = new int[dtSource.Columns.Count];
 77             foreach (DataColumn item in dtSource.Columns)
 78             {
 79                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
 80             }
 81             for (int i = 0; i < dtSource.Rows.Count; i++)
 82             {
 83                 for (int j = 0; j < dtSource.Columns.Count; j++)
 84                 {
 85                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
 86                     if (intTemp > arrColWidth[j])
 87                     {
 88                         arrColWidth[j] = intTemp;
 89                     }
 90                 }
 91             } 
 95             int rowIndex = 0; 
 97             foreach (DataRow row in dtSource.Rows)
 98             {
 99                 #region 新建表,填充表头,填充列头,样式
100                 if (rowIndex == 65535 || rowIndex == 0)
101                 {
102                     if (rowIndex != 0)
103                     {
104                         sheet = workbook.CreateSheet();
105                     }
106 
107                     #region 表头及样式
108                     {
109                         HSSFRow headerRow = sheet.CreateRow(0);
110                         headerRow.HeightInPoints = 25;
111                         headerRow.CreateCell(0).SetCellValue(strHeaderText);
112 
113                         HSSFCellStyle headStyle = workbook.CreateCellStyle();
114                         headStyle.Alignment = CellHorizontalAlignment.CENTER;
115                         HSSFFont font = workbook.CreateFont();
116                         font.FontHeightInPoints = 20;
117                         font.Boldweight = 700;
118                         headStyle.SetFont(font);
119                         headerRow.GetCell(0).CellStyle = headStyle;
120                         sheet.AddMergedRegion(new Region(000, dtSource.Columns.Count - 1));
121                         headerRow.Dispose();
122                     }
123                     #endregion
124 
125 
126                     #region 列头及样式
127                     {
128                         HSSFRow headerRow = sheet.CreateRow(1); 
131                         HSSFCellStyle headStyle = workbook.CreateCellStyle();
132                         headStyle.Alignment = CellHorizontalAlignment.CENTER;
133                         HSSFFont font = workbook.CreateFont();
134                         font.FontHeightInPoints = 10;
135                         font.Boldweight = 700;
136                         headStyle.SetFont(font); 
139                         foreach (DataColumn column in dtSource.Columns)
140                         {
141                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
142                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
143 
144                             //设置列宽
145                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1* 256); 
147                         }
148                         headerRow.Dispose();
149                     }
150                     #endregion
151 
152                     rowIndex = 2;
153                 }
154                 #endregion
155 
156 
157                 #region 填充内容
158                 HSSFRow dataRow = sheet.CreateRow(rowIndex);
159                 foreach (DataColumn column in dtSource.Columns)
160                 {
161                     HSSFCell newCell = dataRow.CreateCell(column.Ordinal);
162 
163                     string drValue = row[column].ToString();
164 
165                     switch (column.DataType.ToString())
166                     {
167                         case "System.String"://字符串类型
168                             newCell.SetCellValue(drValue);
169                             break;
170                         case "System.DateTime"://日期类型
171                             DateTime dateV;
172                             DateTime.TryParse(drValue, out dateV);
173                             newCell.SetCellValue(dateV);
174 
175                             newCell.CellStyle = dateStyle;//格式化显示
176                             break;
177                         case "System.Boolean"://布尔型
178                             bool boolV = false;
179                             bool.TryParse(drValue, out boolV);
180                             newCell.SetCellValue(boolV);
181                             break;
182                         case "System.Int16"://整型
183                         case "System.Int32":
184                         case "System.Int64":
185                         case "System.Byte":
186                             int intV = 0;
187                             int.TryParse(drValue, out intV);
188                             newCell.SetCellValue(intV);
189                             break;
190                         case "System.Decimal"://浮点型
191                         case "System.Double":
192                             double doubV = 0;
193                             double.TryParse(drValue, out doubV);
194                             newCell.SetCellValue(doubV);
195                             break;
196                         case "System.DBNull"://空值处理
197                             newCell.SetCellValue("");
198                             break;
199                         default:
200                             newCell.SetCellValue("");
201                             break;
202                     }
203 
204                 }
205                 #endregion
206 
207                 rowIndex++;
208             } 
211             using (MemoryStream ms = new MemoryStream())
212             {
213                 workbook.Write(ms);
214                 ms.Flush();
215                 ms.Position = 0;
216 
217                 sheet.Dispose();
218                 //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
219                 return ms;
220             } 
222         }
223 
224         /// <summary>
225         /// 用于Web导出
226         /// </summary>
227         /// <param name="dtSource">源DataTable</param>
228         /// <param name="strHeaderText">表头文本</param>
229         /// <param name="strFileName">文件名</param>
230         public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
231         { 
233             HttpContext curContext = HttpContext.Current;
234 
235             // 设置编码和附件格式
236             curContext.Response.ContentType = "application/vnd.ms-excel";
237             curContext.Response.ContentEncoding = Encoding.UTF8;
238             curContext.Response.Charset = "";
239             curContext.Response.AppendHeader("Content-Disposition",
240                 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
241 
242             curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
243             curContext.Response.End(); 
245         } 
247 
248         /// <summary>读取excel
249         /// 默认第一行为标头
250         /// </summary>
251         /// <param name="strFileName">excel文档路径</param>
252         /// <returns></returns>
253         public static DataTable Import(string strFileName)
254         {
255             DataTable dt = new DataTable();
256 
257             HSSFWorkbook hssfworkbook;
258             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
259             {
260                 hssfworkbook = new HSSFWorkbook(file);
261             }
262             HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
263             System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
264 
265             HSSFRow headerRow = sheet.GetRow(0);
266             int cellCount = headerRow.LastCellNum;
267 
268             for (int j = 0; j < cellCount; j++)
269             {
270                 HSSFCell cell = headerRow.GetCell(j);
271                 dt.Columns.Add(cell.ToString());
272             }
273 
274             for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
275             {
276                 HSSFRow row = sheet.GetRow(i);
277                 DataRow dataRow = dt.NewRow();
278 
279                 for (int j = row.FirstCellNum; j < cellCount; j++)
280                 {
281                     if (row.GetCell(j) != null)
282                         dataRow[j] = row.GetCell(j).ToString();
283                 }
284 
285                 dt.Rows.Add(dataRow);
286             }
287             return dt;
288         }
289     }
290 }
291 

 

4、NPOI操作类的调用方法
   DataTable dt_Grade = Tools.Data.GetDataTable(strSQL);
   filename += "绩效考核结果分数统计表";
   PMS.Common.NPOIHelper.ExportByWeb(dt_Grade, filename, filename+".xls");

5、效果展示
   

6、NPOI类库下载:http://files.cnblogs.com/dreamof/NPOIç±»åº�0�9.rar

信息来源:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.html

标签: NPOI
分享到:
评论

相关推荐

    NET使用NPOI组件将数据导出Excel

    NET使用NPOI组件将数据导出Excel

    NPOI组件将数据导出Excel

    NPOI组件将数据导出Excel(多个工作簿) 附带提炼“内库”方法

    ASP.NET使用NPOI导出数据库到Excel文件

    ASP.NET使用NPOI导出数据库到Excel文件,简单方便, 无需Office COM组件且不依赖Office

    EXCEL动态链接库,最新NPOI库,NPOI组件,ASP导出Excel,VB导出Excel,Excel第三方组件

    组件使用NPOI最新版本,优化了NPOI支持表格宽度自适应(支持中文宽度自适应)。 如需在IIS下运行IIS要求IIS6.0以上(支持.net),应用程序池中.NET Framework需要选v4.0。 ASP使用列子参看ASP demo 使用组件需要IIS...

    Asp.Net使用Npoi导入导出Excel的方法

    主要介绍了Asp.Net使用Npoi导入导出Excel的方法,采用该方法在导出Excel的时候不需要office组件的支持,而在导入Excel的时候采用OleDb的方式,需要office组件的支持。是一个非常实用的技巧,需要的朋友可以参考下

    Vue+axios+WebApi+NPOI导出Excel文件实例方法

    项目中前端采用的Element UI 框架, 远程数据请求,使用的是axios,后端接口框架采用的asp.net webapi,数据导出成Excel采用NPOI组件。其业务场景,主要是列表页(如会员信息,订单信息等)表格数据导出,如表格数据...

    最好用的.net导入导出Excel组件NPOI 2.1.3 binary

    NPOI 2.1.3 binary,最好用的导入导出操作excel工具组件,没有之一

    c#导入excel

    在使用Npoi导出Excel的时候,服务器可以不装任何office组件,一般在导出时用到Npoi导出Excel文件,所导Excel也符合规范,打开时也不会有任何文件损坏之类的提示。但是在做导入时还是使用OleDb的方式,这种方式的导入...

    .net mvc HTML导出EXCEL

    另外我加了在MVC中把HTML TABLE导出EXCEL的方法。 调用代码如下: using NPOI; public FileResult GetFile(string html) { html = Server.UrlDecode(html); ExportFile result = new ExportFile...

    ASP.NET中使用开源组件NPOI快速导入导出Execl数据

    主要介绍了ASP.NET中使用开源组件NPOI快速导入导出Execl数据,NPOI是一个很强大的Execl操作组件,需要的朋友可以参考下

    NPOI导出Excel通用方法

    使用三方组件导出Excel,不需要做任何修改把BIN文件夹底下的动态库引用一下就可以直接调用,只需要传数据源、文件名、Excel报表头、报表配置(这个根据不同要求去调整,主要是用作配置列宽的)。如果还有什么不理解...

    C# 操作excel 用的NPOI 组件包

    C# 操作excel 用的NPOI 开源组件包 ,版本号2.0.1.0。 1、您可以完全免费使用该框架 2、包含了大部分EXCEL的特性(单元格样式、数据格式、公式等等) 3、专业的技术支持服务(24*7全天候) (非免费) 4、支持处理的文件...

    Npoi生成Excel 97-2003/ (xls)文件

    NPOI 是 POI 项目的 .NET... 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。

    NPOI_2.5.1最新完整包(包含NPOI、Portable.BouncyCastle、SharpZipLib)

    NPOI 2.5.1版本,最新完整包,包含...POI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目,支持Excel大数据量导出。 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。

    免费DataGridView打印及.NET轻松打印控件5.7版(VB打印,C#打印,Excel导入导出,多表头显示与打印)

    其中导入Excel功能使用开源的NPOI组件实现,不依赖Office。 4、其他一些完善,比如解决了导出Excel时强制换行不自动显示,而是要双击才显示问题;导出Excel时,图片能按单元格大小导出。 本控件特色: 1、强大的...

    NPOI2.2.zip

     NPOI之所以强大,并不是因为它支持导出Excel,而是因为它支持导入Excel,并能"理解"OLE2文档结构,这也是其他一些Excel读写库比较弱的方面。通常,读入并理解结构远比导出来得复杂,因为导入你必须假设一切情况都...

    asp.net+Web+mvc4.0 EasyUI 最新 权限管理系统源码教程

    6、文档方案(均为开源) 导出:Excel2007使用EPPlus、Excel2003使用NPOI、Word2003/2007使用DocX、Pdf使用Gios 压缩:Ionic.Zip、Ziplib 7、js库为jquery 8、UI选用jquery easyui 1.3.2 9、选knockoutjs为前端...

    下载你就赚到了npoi

    我以前在做C#项目时遇到过导出数据成Excel文件的问题,曾经用过office的组件,后来又用Aspose.Cells控件。Aspose.Cells是很强大,但是要收费的。平时做些小程序时也在用它,用的是破解版。只是感觉它的功能过于强大...

Global site tag (gtag.js) - Google Analytics