NPOI 生成Excel 的——常用

2024-04-06 22:18
文章标签 excel 生成 常用 npoi

本文主要是介绍NPOI 生成Excel 的——常用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

把自己常用的整理了出来,(*^__^*) 嘻嘻……

有关文件输出文件名乱码的问题

有设置Excel中的一些样式问题

有直接保存Excel的

更多NPOI的实例说明:http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html   这个可是别个大虾滴。

[csharp] view plain copy print ?
  1. using System; 
  2. using System.Collections; 
  3. using System.Configuration; 
  4. using System.Data; 
  5. using System.Web; 
  6. using System.Web.Security; 
  7. using System.Web.UI; 
  8. using System.Web.UI.HtmlControls; 
  9. using System.Web.UI.WebControls; 
  10. using System.Web.UI.WebControls.WebParts; 
  11.  
  12. using System.IO; 
  13. using NPOI.SS.UserModel; 
  14. using NPOI.HSSF.UserModel; 
  15. using NPOI.HSSF.Util; 
  16.  
  17. public partial class _Default : System.Web.UI.Page 
  18.     protected void Page_Load(object sender, EventArgs e) 
  19.     { 
  20.         DownLoadExcel(); 
  21.     } 
  22.  
  23.     /// <summary> 
  24.     /// 下载Excel 
  25.     /// </summary> 
  26.     public void DownLoadExcel() 
  27.     { 
  28.         /*
  29.          * ①:输出文档
  30.          */ 
  31.         string fileName = DateTime.Now.ToString("yyyyMMdd") + "测试.xls"
  32.  
  33.         string UserAgent = Request.ServerVariables["http_user_agent"].ToLower(); 
  34.         // Firfox和IE下输出中文名显示正常 
  35.         if (UserAgent.IndexOf("firefox") == -1) 
  36.         { 
  37.             fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); 
  38.         } 
  39.  
  40.         Response.ContentType = "application/vnd.ms-excel;charset=UTF-8"
  41.         Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); 
  42.         Response.Clear(); 
  43.         //写入内容到Excel 
  44.         HSSFWorkbook hssfworkbook = writeToExcel(); 
  45.         //将Excel内容写入到流中 
  46.         MemoryStream file = new MemoryStream(); 
  47.         hssfworkbook.Write(file); 
  48.         //输出 
  49.         Response.BinaryWrite(file.GetBuffer()); 
  50.         Response.End(); 
  51.  
  52.         /*
  53.          * ②:将文档保存到指定路径
  54.          */ 
  55.         string destFileName = @"D:\test.xls"
  56.         HSSFWorkbook hssfworkbook2 = writeToExcel(); 
  57.         MemoryStream msfile = new MemoryStream(); 
  58.         hssfworkbook.Write(msfile); 
  59.         System.IO.File.WriteAllBytes(destFileName, msfile.ToArray()); 
  60.     } 
  61.  
  62.     /// <summary> 
  63.     /// 写入内容到Excel中 
  64.     /// </summary> 
  65.     /// <returns></returns> 
  66.     private HSSFWorkbook writeToExcel() 
  67.     { 
  68.         //string template = "模板路径.xls"; 
  69.         //FileStream file = new FileStream(template, FileMode.Open, FileAccess.Read); 
  70.         //HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);// 创建对象 
  71.         //HSSFSheet excelSheet = (HSSFSheet)hssfworkbook.GetSheetAt(0);// 获得sheet 
  72.  
  73.         HSSFWorkbook hssfworkbook = new HSSFWorkbook(); 
  74.  
  75.         HSSFSheet excelSheet = (HSSFSheet)hssfworkbook.CreateSheet("sheet1"); 
  76.  
  77.         Row row0 = excelSheet.CreateRow(0); 
  78.         Cell cell0 = CreateCell(0, row0); 
  79.         cell0.SetCellValue("NUM"); 
  80.         cell0.CellStyle = GetCellStyle(hssfworkbook, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, HSSFColor.LIGHT_YELLOW.index, "#,##0"); 
  81.  
  82.         for (int i = 100, j = 1; i < 10000; i++, j++) 
  83.         { 
  84.             Row row = CreateRow(j, excelSheet); 
  85.             Cell cell = CreateCell(0, row); 
  86.             cell.SetCellValue(i); 
  87.             cell.CellStyle = GetCellStyle(hssfworkbook, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, HSSFColor.LIGHT_GREEN.index, "#,##0"); 
  88.         } 
  89.  
  90.         return hssfworkbook; 
  91.     } 
  92.  
  93.  
  94.     /// <summary> 
  95.     /// 设置样式 
  96.     /// </summary> 
  97.     /// <param name="hssfworkbook"></param> 
  98.     /// <param name="borderLeft">左边框</param> 
  99.     /// <param name="borderBottom">下边框</param> 
  100.     /// <param name="borderRight">右边框</param> 
  101.     /// <param name="borderTop">上边框</param> 
  102.     /// <param name="fillforgeroundColor">背景填充色</param> 
  103.     /// <param name="dataFormat">数据格式</param> 
  104.     /// <returns></returns> 
  105.     private CellStyle GetCellStyle(HSSFWorkbook hssfworkbook 
  106.         , CellBorderType borderLeft, CellBorderType borderBottom, CellBorderType borderRight, CellBorderType borderTop 
  107.         , short fillforgeroundColor 
  108.         , string dataFormat) 
  109.     { 
  110.         CellStyle styleInfo = hssfworkbook.CreateCellStyle(); 
  111.  
  112.         styleInfo.BorderLeft = borderLeft; 
  113.         styleInfo.BorderBottom = borderBottom; 
  114.         styleInfo.BorderRight = borderRight; 
  115.         styleInfo.BorderTop = borderTop; 
  116.  
  117.         styleInfo.Alignment = HorizontalAlignment.CENTER; 
  118.         styleInfo.VerticalAlignment = VerticalAlignment.CENTER; 
  119.  
  120.         styleInfo.FillForegroundColor = fillforgeroundColor;//设置填充色 
  121.         styleInfo.FillPattern = FillPatternType.SOLID_FOREGROUND;//设置填充色的时候必须设置这个 
  122.  
  123.         styleInfo.DataFormat = HSSFDataFormat.GetBuiltinFormat(dataFormat); 
  124.         // 当前日期格式的需要以下这样设置 
  125.         //HSSFDataFormat format = (HSSFDataFormat)hssfworkbook.CreateDataFormat(); 
  126.         //styleInfo.DataFormat = format.GetFormat("yyyy年m月d日"); 
  127.  
  128.         return styleInfo; 
  129.     } 
  130.  
  131.     /// <summary> 
  132.     /// 创建行对象 
  133.     /// </summary> 
  134.     /// <param name="rowID"></param> 
  135.     /// <param name="excelSheet"></param> 
  136.     /// <returns></returns> 
  137.     private Row CreateRow(int rowID, HSSFSheet excelSheet) 
  138.     { 
  139.         Row row = excelSheet.GetRow(rowID); 
  140.         if (row == null
  141.         { 
  142.             row = excelSheet.CreateRow(rowID); 
  143.         } 
  144.         return row; 
  145.     } 
  146.  
  147.     /// <summary> 
  148.     /// 创建列对象 
  149.     /// </summary> 
  150.     /// <param name="rowID"></param> 
  151.     /// <param name="excelSheet"></param> 
  152.     /// <returns></returns> 
  153.     private Cell CreateCell(int cellID, Row row) 
  154.     { 
  155.         Cell cell = row.GetCell(cellID); 
  156.         if (cell == null
  157.         { 
  158.             cell = row.CreateCell(cellID); 
  159.         } 
  160.         return cell; 
  161.     } 
  162.  
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;public partial class _Default : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e){DownLoadExcel();}/// <summary>/// 下载Excel/// </summary>public void DownLoadExcel(){/** ①:输出文档*/string fileName = DateTime.Now.ToString("yyyyMMdd") + "测试.xls";string UserAgent = Request.ServerVariables["http_user_agent"].ToLower();// Firfox和IE下输出中文名显示正常if (UserAgent.IndexOf("firefox") == -1){fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);}Response.ContentType = "application/vnd.ms-excel;charset=UTF-8";Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));Response.Clear();//写入内容到ExcelHSSFWorkbook hssfworkbook = writeToExcel();//将Excel内容写入到流中MemoryStream file = new MemoryStream();hssfworkbook.Write(file);//输出Response.BinaryWrite(file.GetBuffer());Response.End();/** ②:将文档保存到指定路径*/string destFileName = @"D:\test.xls";HSSFWorkbook hssfworkbook2 = writeToExcel();MemoryStream msfile = new MemoryStream();hssfworkbook.Write(msfile);System.IO.File.WriteAllBytes(destFileName, msfile.ToArray());}/// <summary>/// 写入内容到Excel中/// </summary>/// <returns></returns>private HSSFWorkbook writeToExcel(){//string template = "模板路径.xls";//FileStream file = new FileStream(template, FileMode.Open, FileAccess.Read);//HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);// 创建对象//HSSFSheet excelSheet = (HSSFSheet)hssfworkbook.GetSheetAt(0);// 获得sheetHSSFWorkbook hssfworkbook = new HSSFWorkbook();HSSFSheet excelSheet = (HSSFSheet)hssfworkbook.CreateSheet("sheet1");Row row0 = excelSheet.CreateRow(0);Cell cell0 = CreateCell(0, row0);cell0.SetCellValue("NUM");cell0.CellStyle = GetCellStyle(hssfworkbook, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, HSSFColor.LIGHT_YELLOW.index, "#,##0");for (int i = 100, j = 1; i < 10000; i++, j++){Row row = CreateRow(j, excelSheet);Cell cell = CreateCell(0, row);cell.SetCellValue(i);cell.CellStyle = GetCellStyle(hssfworkbook, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, CellBorderType.THIN, HSSFColor.LIGHT_GREEN.index, "#,##0");}return hssfworkbook;}/// <summary>/// 设置样式/// </summary>/// <param name="hssfworkbook"></param>/// <param name="borderLeft">左边框</param>/// <param name="borderBottom">下边框</param>/// <param name="borderRight">右边框</param>/// <param name="borderTop">上边框</param>/// <param name="fillforgeroundColor">背景填充色</param>/// <param name="dataFormat">数据格式</param>/// <returns></returns>private CellStyle GetCellStyle(HSSFWorkbook hssfworkbook, CellBorderType borderLeft, CellBorderType borderBottom, CellBorderType borderRight, CellBorderType borderTop, short fillforgeroundColor, string dataFormat){CellStyle styleInfo = hssfworkbook.CreateCellStyle();styleInfo.BorderLeft = borderLeft;styleInfo.BorderBottom = borderBottom;styleInfo.BorderRight = borderRight;styleInfo.BorderTop = borderTop;styleInfo.Alignment = HorizontalAlignment.CENTER;styleInfo.VerticalAlignment = VerticalAlignment.CENTER;styleInfo.FillForegroundColor = fillforgeroundColor;//设置填充色styleInfo.FillPattern = FillPatternType.SOLID_FOREGROUND;//设置填充色的时候必须设置这个styleInfo.DataFormat = HSSFDataFormat.GetBuiltinFormat(dataFormat);// 当前日期格式的需要以下这样设置//HSSFDataFormat format = (HSSFDataFormat)hssfworkbook.CreateDataFormat();//styleInfo.DataFormat = format.GetFormat("yyyy年m月d日");return styleInfo;}/// <summary>/// 创建行对象/// </summary>/// <param name="rowID"></param>/// <param name="excelSheet"></param>/// <returns></returns>private Row CreateRow(int rowID, HSSFSheet excelSheet){Row row = excelSheet.GetRow(rowID);if (row == null){row = excelSheet.CreateRow(rowID);}return row;}/// <summary>/// 创建列对象/// </summary>/// <param name="rowID"></param>/// <param name="excelSheet"></param>/// <returns></returns>private Cell CreateCell(int cellID, Row row){Cell cell = row.GetCell(cellID);if (cell == null){cell = row.CreateCell(cellID);}return cell;}}


最近被Excel的給整疯了。

整理一下,希望可以给人帮助!

这篇关于NPOI 生成Excel 的——常用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/880964

相关文章

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2