1. 程式人生 > >C#匯出Excel(使用NPOI)

C#匯出Excel(使用NPOI)

        之前在C#網站或Webservice程式中一直使用COM元件的方式匯出Excel檔案,但是經常會出現除錯成功,但是部署到伺服器之後就失敗的現象。如果伺服器不是自己的,而要你到甲方那裡去部署,出現這種現象就尷尬了尷尬。後來發現NPOI外掛非常好用,這裡總結一下。

        下面是對NPOI常用方法做的一個封裝類,可以直接使用。

using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ExcelHelper
{
    public class ExcelHelp
    {
        public static NPOI.HSSF.UserModel.HSSFWorkbook obook;
        public static NPOI.SS.UserModel.ISheet osheet;

        /// <summary>
        /// 建構函式,初始化表單物件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="sheetname"></param>
        public ExcelHelp()
        {
                obook = new NPOI.HSSF.UserModel.HSSFWorkbook();
                osheet = obook.CreateSheet("sheet1");
        }

        /// <summary>
        /// 合併單元格
        /// </summary>
        /// <param name="r1">左上角單元格行標(從0開始,下同)</param>
        /// <param name="c1">左上角單元格列標</param>
        /// <param name="r2">右下角單元格行標</param>
        /// <param name="c2">右下角單元格列標</param>
        public void Merge( int r1,int c1,int r2,int c2)
        {
            osheet.AddMergedRegion(new CellRangeAddress(r1, c1, r2, c2));
        }
        /// <summary>
        /// 設定單元格內容
        /// </summary>
        /// <param name="row">單元格行標(從0開始,下同)</param>
        /// <param name="col">單元格列標</param>
        /// <param name="o">寫入內容</param>
        public void SetValue( int r, int c, object o)
        {
            if (o != null)
            {
                if(r<=osheet.LastRowNum)
                {
                    IRow row = osheet.GetRow(r);
                    if (row == null)
                    {
                        row = osheet.CreateRow(r);
                        row.HeightInPoints = 14;
                    }
                    if(c<=row.LastCellNum)
                    {
                        ICell cell = row.GetCell(c);
                        cell.SetCellValue(o.ToString());
                    }
                    else
                    {
                        for(int j=row.LastCellNum;j<c;j++)
                        {
                            row.CreateCell(j + 1);
                            ICell cell22 = row.GetCell(j + 1);
                            ICellStyle style = obook.CreateCellStyle();
                            cell22.CellStyle = style;
                        }
                        ICell cell = row.GetCell(c);
                        cell.SetCellValue(o.ToString());
                    }
                }
                else
                {
                    for (int i = osheet.LastRowNum; i < r; i++)
                    {
                        IRow row22 = osheet.CreateRow(i + 1);
                        row22.HeightInPoints = 14;
                    }
                    IRow row = osheet.GetRow(r);
                    for (int j = row.LastCellNum; j < c; j++)
                    {
                        row.CreateCell(j + 1); ;
                        ICell cell22 = row.GetCell(j + 1);
                        ICellStyle style = obook.CreateCellStyle();
                        cell22.CellStyle = style;
                    }
                    ICell cell = row.GetCell(c);
                    cell.SetCellValue(o.ToString());
                    
                }

            }
        }
        /// <summary>
        /// 設定行高
        /// </summary>
        /// <param name="r">行數</param>
        /// <param name="height">高度</param>
        public void SetRowHeight(int r,int height)
        {
            if (r <= osheet.LastRowNum)
            {
                IRow row = osheet.GetRow(r);
                if (row != null)
                {
                    row.HeightInPoints = height;
                }
            }
        }
        /// <summary>
        /// 設定字型寬度
        /// </summary>
        /// <param name="c">列標</param>
        /// <param name="width">寬度值(例如設定為1,表示一個英文字元的寬度)</param>
        public void SetCollumWdith(int c, int width)
        {
            osheet.SetColumnWidth(c, 256 * width);
        }
        /// <summary>
        /// 設定單元格對齊方式
        /// </summary>
        /// <param name="r">行標</param>
        /// <param name="c">列標</param>
        /// <param name="align">對齊方式('L',左對齊;'C'居中;'R'右對齊)</param>
        public void SetCellAlignment(int r, int c, char align)
        {
            if(r<=osheet.LastRowNum)
            {
                IRow row = osheet.GetRow(r);
                if(row!=null)
                {
                    if(c<=row.LastCellNum)
                    {
                        ICell cell = row.GetCell(c);
                        ICellStyle style = cell.CellStyle;
                        //設定單元格的樣式:水平對齊居中
                        if (align == 'C')
                            style.Alignment = HorizontalAlignment.Center;
                        else if (align == 'L')
                            style.Alignment = HorizontalAlignment.Left;
                        else if (align == 'R')
                            style.Alignment = HorizontalAlignment.Right;
                        cell.CellStyle = style;
                    }
                }
            }
        }

        /// <summary>
        /// 設定字型樣式
        /// </summary>
        /// <param name="r">行標</param>
        /// <param name="c">列標</param>
        /// <param name="size">字型大小,0為預設</param>
        /// <param name="f">字型樣式(‘B’加粗,‘I’斜體)</param>
        /// <param name="color">字型顏色('R'紅,'B'藍,'G'綠,'Y'黃,'P'粉,'O'橙,'W'白)</param>
        public void SetCellFont(int r, int c,int size, char f,char color)
        {
            if (r <= osheet.LastRowNum)
            {
                IRow row = osheet.GetRow(r);
                if (row != null)
                {
                    if (c <= row.LastCellNum)
                    {
                        ICell cell = row.GetCell(c);
                        ICellStyle style = cell.CellStyle;
                        //新建一個字型樣式物件
                        IFont font = obook.CreateFont();
                        //設定字型大小
                        if(size>0)
                            font.FontHeightInPoints = Convert.ToInt16(size);
                        switch (f)
                        {
                            case 'B':
                                {
                                    //設定字型加粗樣式
                                    font.IsBold = true;
                                } break;
                            case 'I':
                                {
                                    //設定字型加粗樣式
                                    font.IsItalic = true;
                                } break;
                        }
                        switch (color)
                        {
                            case 'R': { font.Color = HSSFColor.Red.Index; } break;
                            case 'B': { font.Color = HSSFColor.Blue.Index; } break;
                            case 'G': { font.Color = HSSFColor.Green.Index; } break;
                            case 'Y': { font.Color = HSSFColor.Yellow.Index; } break;
                            case 'P': { font.Color = HSSFColor.Pink.Index; } break;
                            case 'O': { font.Color = HSSFColor.Orange.Index; } break;
                            case 'W': { font.Color = HSSFColor.White.Index; } break;
                        }
                        //使用SetFont方法將字型樣式新增到單元格樣式中 
                        style.SetFont(font);
                        //將新的樣式賦給單元格
                        cell.CellStyle = style;
                    }
                }
            }
        }

        /// <summary>
        /// 寫入到Excel文件
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool ExportToExcel(string path)
        {
            try
            {
                // 寫入到客戶端  
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    obook.Write(fs);
                }
                return true;
            }
            catch { return false; }
        }

        public void Dispose()
        {
            obook.Close();
            GC.Collect();
        }
    }
}
    下面是呼叫方法,很簡單了
          ExcelHelper.ExcelHelp myexcel = new ExcelHelper.ExcelHelp();
            try
            {
                myexcel.Merge(0, 0, 0, 3);
                myexcel.SetValue(0, 0, "你好");
                myexcel.SetRowHeight(0, 25);
                myexcel.SetCellAlignment(0, 0, 'C');
                myexcel.SetCellFont(0, 0, 20,'B','R');
                myexcel.SetValue(3, 0, "你好");
                myexcel.SetValue(10, 5, "你好");
                myexcel.SetCollumWdith(4, 20);
                myexcel.ExportToExcel("D:\\aaaabc.xls");
            }
            catch { }
            finally { myexcel.Dispose(); }
注意,這裡是winform的呼叫方法,如果是網頁(asp.net)匯出,函式ExportToExcel應該改寫為下面的形式:
System.IO.MemoryStream ms = new System.IO.MemoryStream();
obook.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();