1. 程式人生 > >使用NPOI操作Excel檔案及其日期處理

使用NPOI操作Excel檔案及其日期處理

工作中經常遇到需要讀取或匯出Excel檔案的情況,而NPOI是目前最宜用、效率最高的操作的Office(不只是Excel喲)檔案的元件,使用方便,不詳細說明了。

Excel工作表約定:整個Excel表格叫做工作表:WorkBook(工作薄),包含的叫頁(工作表):Sheet;行:Row;單元格Cell。

1、先上一個Excel2003的例子,程式碼如下:

//讀取xls檔案
        private void button2_Click(object sender, EventArgs e)
        {   StringBuilder sbr = new StringBuilder();


            using (FileStream fs = File.OpenRead(@"c:/myxls.xls"))   //開啟myxls.xls檔案
            {
                HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls檔案中的資料寫入wk中
                for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中總共的表數
                {
                    ISheet sheet = wk.GetSheetAt(i);   //讀取當前表資料

                    for (int j = 0; j <= sheet.LastRowNum; j++)  //LastRowNum 是當前表的總行數
                    {
                        IRow row = sheet.GetRow(j);  //讀取當前行資料
                        if (row != null)
                        {
                            sbr.Append("-------------------------------------\r\n"); //讀取行與行之間的提示界限

                            for (int k = 0; k <= row.LastCellNum; k++)  //LastCellNum 是當前行的總列數
                            {
                                ICell cell = row.GetCell(k);  //當前表格
                                if (cell != null)
                                {                                   
                                    sbr.Append(cell.ToString());   //獲取表格中的資料並轉換為字串型別
                                }
                            }
                        }
                    }
                }               
            }
            sbr.ToString();
            using (StreamWriter wr = new StreamWriter(new FileStream(@"c:/myText.txt", FileMode.Append)))  //把讀取xls檔案的資料寫入myText.txt檔案中
            {
                wr.Write(sbr.ToString());
                wr.Flush();
            }
        }

//建立一個常用的xls檔案
        private void button3_Click(object sender, EventArgs e)
        {          
            IWorkbook wb = new HSSFWorkbook();
            //建立表  
            ISheet sh = wb.CreateSheet("zhiyuan");
            //設定單元的寬度  
            sh.SetColumnWidth(0, 15 * 256);
            sh.SetColumnWidth(1, 35 * 256);
            sh.SetColumnWidth(2, 15 * 256);
            sh.SetColumnWidth(3, 10 * 256);
            int i = 0;
            #region 練習合併單元格
            sh.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 3));

            //CellRangeAddress()該方法的引數次序是:開始行號,結束行號,開始列號,結束列號。
            IRow row0 = sh.CreateRow(0);
            row0.Height = 20 * 20;
            ICell icell1top0 = row0.CreateCell(0);
            icell1top0.CellStyle = Getcellstyle(wb, stylexls.頭);
            icell1top0.SetCellValue("標題合併單元");
            #endregion
            i++;
            #region 設定表頭
            IRow row1 = sh.CreateRow(1);
            row1.Height = 20 * 20;

            ICell icell1top = row1.CreateCell(0);
            icell1top.CellStyle = Getcellstyle(wb, stylexls.頭);
            icell1top.SetCellValue("網站名");

            ICell icell2top = row1.CreateCell(1);
            icell2top.CellStyle = Getcellstyle(wb, stylexls.頭);
            icell2top.SetCellValue("網址");

            ICell icell3top = row1.CreateCell(2);
            icell3top.CellStyle = Getcellstyle(wb, stylexls.頭);
            icell3top.SetCellValue("百度快照");

            ICell icell4top = row1.CreateCell(3);
            icell4top.CellStyle = Getcellstyle(wb, stylexls.頭);
            icell4top.SetCellValue("百度收錄");
            #endregion  
            using(FileStream stm=File.OpenWrite(@"c:/myMergeCell.xls"))
            {
                wb.Write(stm); 
                MessageBox.Show("提示:建立成功!");
            }
        } 

        #region 定義單元格常用到樣式的列舉
        public enum stylexls
        {
            頭,
            url,
            時間,
            數字,
            錢,
            百分比,
            中文大寫,
            科學計數法,
            預設
        }
        #endregion


        #region 定義單元格常用到樣式
        static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)
        {
            ICellStyle cellStyle = wb.CreateCellStyle();

            //定義幾種字型  
            //也可以一種字型,寫一些公共屬性,然後在下面需要時加特殊的  
            IFont font12 = wb.CreateFont();
            font12.FontHeightInPoints = 10;
            font12.FontName = "微軟雅黑";


            IFont font = wb.CreateFont();
            font.FontName = "微軟雅黑";
            //font.Underline = 1;下劃線 


            IFont fontcolorblue = wb.CreateFont();
            fontcolorblue.Color = HSSFColor.OLIVE_GREEN.BLUE.index;
            fontcolorblue.IsItalic = true;//下劃線  
            fontcolorblue.FontName = "微軟雅黑";

            //邊框  
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.DOTTED;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.HAIR;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.HAIR;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.DOTTED;
            //邊框顏色  
            cellStyle.BottomBorderColor = HSSFColor.OLIVE_GREEN.BLUE.index;
            cellStyle.TopBorderColor = HSSFColor.OLIVE_GREEN.BLUE.index;

            //背景圖形,我沒有用到過。感覺很醜  
            //cellStyle.FillBackgroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;  
            //cellStyle.FillForegroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;  
            cellStyle.FillForegroundColor = HSSFColor.WHITE.index;
            // cellStyle.FillPattern = FillPatternType.NO_FILL;  
            cellStyle.FillBackgroundColor = HSSFColor.BLUE.index;

            //水平對齊  
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;

            //垂直對齊  
            cellStyle.VerticalAlignment = VerticalAlignment.CENTER;

            //自動換行  
            cellStyle.WrapText = true;

            //縮排;當設定為1時,前面留的空白太大了。希旺官網改進。或者是我設定的不對  
            cellStyle.Indention = 0;

            //上面基本都是設共公的設定  


            //下面列出了常用的欄位型別  
            switch (str)
            {
                case stylexls.頭:
                    // cellStyle.FillPattern = FillPatternType.LEAST_DOTS;  
                    cellStyle.SetFont(font12);
                    break;
                case stylexls.時間:
                    IDataFormat datastyle = wb.CreateDataFormat();

                    cellStyle.DataFormat = datastyle.GetFormat("yyyy/mm/dd");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.數字:
                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.錢:
                    IDataFormat format = wb.CreateDataFormat();
                    cellStyle.DataFormat = format.GetFormat("¥#,##0");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.url:
                    fontcolorblue.Underline = 1;
                    cellStyle.SetFont(fontcolorblue);
                    break;
                case stylexls.百分比:
                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.中文大寫:
                    IDataFormat format1 = wb.CreateDataFormat();
                    cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.科學計數法:
                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.預設:
                    cellStyle.SetFont(font);
                    break;
            }
            return cellStyle;

        }
        #endregion

2、再來一個Excel2007的並繫結到GridView中例子,程式碼如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.IO;

using NPOI.SS.UserModel;

using NPOI.HSSF.Util;

using NPOI.HSSF.UserModel;

using NPOI.XSSF.UserModel;

/// <summary>

///NPOI操作Excel,這個例子是針對Excel 2007. 

/// </summary>

public class ExcelHelper{

    IWorkbook hssfworkbook;

    public DataTable ImportExcelFile(string filePath)

    {

        #region//初始化資訊

        try

        {

            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))

            {

                hssfworkbook = new XSSFWorkbook(file);

            }

        }

        catch (Exception e)

        {

            throw e;

        }

        #endregion

        ISheet sheet = hssfworkbook.GetSheetAt(0);

        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

        DataTable dt = new DataTable();

        //一行最後一個方格的編號 即總的列數

        for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)

        {

            dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());

        }

        while (rows.MoveNext())

        {

            IRow row = (XSSFRow)rows.Current;

            DataRow dr = dt.NewRow();

            for (int i = 0; i < row.LastCellNum; i++)

            {

                ICell cell = row.GetCell(i);

                if (cell == null)

                {

                    dr[i] = null;

                }

                else

                {

                    dr[i] = cell.ToString();

                }

            }

            dt.Rows.Add(dr);

        }

        return dt;

    }

    hssfworkbook= null;

    sheet = null; 

}

    //繫結GridView顯示只需要兩名程式碼

    this.gvExcel.DataSource = dt;

    this.gvExcel.DataBind();

3、NPOI中的日期處理,NOPI版本為2.0.2。

POI對單元格日期處理很弱,沒有針對的型別,日期型別取出來的也是一個double值,所以同樣作為數值型別。

/**

*Excel中的日期格式在解析為DataTable時會依格式不同解析為不同的值,因為所有的日期格式都可以通過下面DataFormat來判斷,

*excel2013,測試結果如下:*時分(HH:mm) - 20,時間(HH:mm:ss) - 21,日期時間(yyyy-MM-dd HH:mm:ss) - 22,

*年月(yyyy-MM) - 17,年月日(yyyy-MM-dd)-14,yyyy年m月-------57,月日(MM-dd) - 58,

*yyyy年m月d日---31,h時mm分  -------32

* */

 if (cell.CellType == CellType.NUMERIC)

 {

      short format = cell.CellStyle.DataFormat;

      if (format == 14 || format == 31 || format == 57 || format == 58)

      {

          DateTime date = cell.DateCellValue;

          string re = date.ToString("yyy-MM-dd");

       }