NPOI 生成Excel 的——常用

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

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

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

有直接保存Excel的

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

  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();
        //写入内容到Excel
        HSSFWorkbook 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);// 获得sheet

        HSSFWorkbook 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的給整疯了。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值