1. 程式人生 > 實用技巧 >C# 讀寫Excel(NPOI庫)

C# 讀寫Excel(NPOI庫)

一、什麼是NPOI

  NPOI是開源的POI專案的.NET版,可以用來讀寫Excel,Word,PPT檔案。在處理Excel檔案上,NPOI 可以同時相容 xls 和 xlsx。官網提供了一份Examples,給出了很多應用場景的例子,打包好的二進位制檔案類庫,也僅有幾MB,使用非常方便。

二、讀Excel

  NPOI 使用HSSFWorkbook類來處理 xls,XSSFWorkbook類來處理 xlsx,它們都繼承介面IWorkbook,因此可以通過IWorkbook來統一處理 xls 和 xlsx 格式的檔案。

  以下是簡單的例子

public void ReadFromExcelFile(string
filePath) { IWorkbook wk = null; string extension = Path.GetExtension(filePath); try { FileStream fs = File.OpenRead(filePath); if (extension.Equals(".xls")) { //把xls檔案中的資料寫入wk中
wk = new HSSFWorkbook(fs); } else { //把xlsx檔案中的資料寫入wk中 wk = new XSSFWorkbook(fs); } fs.Close(); //讀取當前表資料 ISheet sheet = wk.GetSheetAt(0
); IRow row = sheet.GetRow(0); //讀取當前行資料 for (int i = 0; i <= sheet.LastRowNum; i++) //LastRowNum 是當前表的總行數-1(注意) { row = sheet.GetRow(i); //讀取當前行資料 if (row != null) { //LastCellNum 是當前行的總列數 for (int j = 0; j < row.LastCellNum; j++) { //讀取該行的第j列資料 string value = row.GetCell(j).ToString(); Console.Write(value.ToString() + " "); } Console.WriteLine("\n"); } } Console.ReadKey(); } catch (Exception e) { //只在Debug模式下才輸出 Console.WriteLine(e.Message); } }

  Excel中的單元格是有不同資料格式的,例如數字,日期,字串等,在讀取的時候可以根據格式的不同設定物件的不同型別,方便後期的資料處理。

//獲取cell的資料,並設定為對應的資料型別
public object GetCellValue(ICell cell)
{
    object value = null;
    try
    {
        if (cell.CellType != CellType.Blank)
        {
            switch (cell.CellType)
            {
                case CellType.Numeric:
                    // Date comes here
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        value = cell.DateCellValue;
                    }
                    else
                    {
                        // Numeric type
                        value = cell.NumericCellValue;
                    }
                    break;
                case CellType.Boolean:
                    // Boolean type
                    value = cell.BooleanCellValue;
                    break;
                case CellType.Formula:
                    value = cell.CellFormula;
                    break;
                default:
                    // String type
                    value = cell.StringCellValue;
                    break;
            }
        }
    }
    catch (Exception)
    {
        value = "";
    }

    return value;
}

  特別注意的是CellType中沒有Date,而日期型別的資料型別是Numeric,其實日期的資料在Excel中也是以數字的形式儲存。可以使用DateUtil.IsCellDateFormatted方法來判斷是否是日期型別。

  有了GetCellValue方法,寫資料到Excel中的時候就要有SetCellValue方法,缺的型別可以自己補。

//根據資料型別設定不同型別的cell
        public static void SetCellValue(ICell cell, object obj)
        {
            if (obj.GetType() == typeof(int))
            {
                cell.SetCellValue((int)obj);
            }
            else if (obj.GetType() == typeof(double))
            {
                cell.SetCellValue((double)obj);
            }
            else if (obj.GetType() == typeof(IRichTextString))
            {
                cell.SetCellValue((IRichTextString)obj);
            }
            else if (obj.GetType() == typeof(string))
            {
                cell.SetCellValue(obj.ToString());
            }
            else if (obj.GetType() == typeof(DateTime))
            {
                cell.SetCellValue((DateTime)obj);
            }
            else if (obj.GetType() == typeof(bool))
            {
                cell.SetCellValue((bool)obj);
            }
            else
            {
                cell.SetCellValue(obj.ToString());
            }
        }

  cell.SetCellValue()方法只有四種過載方法,引數分別是string,bool,DateTime,double,IRichTextString
設定公式使用cell.SetCellFormula(string formula)

三、寫Excel

  以下是簡單的例子,更多資訊可以參見官網提供的Examples

 public void WriteToExcel(string filePath)
        {
            //建立工作薄  
            IWorkbook wb;
            string extension = System.IO.Path.GetExtension(filePath);
            //根據指定的檔案格式建立對應的類
            if (extension.Equals(".xls"))
            {
                wb = new HSSFWorkbook();
            }
            else
            {
                wb = new XSSFWorkbook();
            }

            ICellStyle style1 = wb.CreateCellStyle();//樣式
            style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊方式
            style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊方式
                                                                                  //設定邊框
            style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            style1.WrapText = true;//自動換行

            ICellStyle style2 = wb.CreateCellStyle();//樣式
            IFont font1 = wb.CreateFont();//字型
            font1.FontName = "楷體";
            font1.Color = HSSFColor.Red.Index;//字型顏色
            font1.Boldweight = (short)FontBoldWeight.Normal;//字型加粗樣式
            style2.SetFont(font1);//樣式裡的字型設定具體的字型樣式
                                  //設定背景色
            style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
            style2.FillPattern = FillPattern.SolidForeground;
            style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
            style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊方式
            style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊方式

            ICellStyle dateStyle = wb.CreateCellStyle();//樣式
            dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平對齊方式
            dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直對齊方式
                                                                                     //設定資料顯示格式
            IDataFormat dataFormatCustom = wb.CreateDataFormat();
            dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss");

            //建立一個表單
            ISheet sheet = wb.CreateSheet("Sheet0");
            //設定列寬
            int[] columnWidth = { 10, 10, 20, 10 };
            for (int i = 0; i < columnWidth.Length; i++)
            {
                //設定列寬度,256*字元數,因為單位是1/256個字元
                sheet.SetColumnWidth(i, 256 * columnWidth[i]);
            }

            //測試資料
            int rowCount = 3, columnCount = 4;
            object[,] data = {
        {"列0", "列1", "列2", "列3"},
        {"", 400, 5.2, 6.01},
        {"", true, "2014-07-02", DateTime.Now}
        //日期可以直接傳字串,NPOI會自動識別
        //如果是DateTime型別,則要設定CellStyle.DataFormat,否則會顯示為數字
    };

            IRow row;
            ICell cell;

            for (int i = 0; i < rowCount; i++)
            {
                row = sheet.CreateRow(i);//建立第i行
                for (int j = 0; j < columnCount; j++)
                {
                    cell = row.CreateCell(j);//建立第j列
                    cell.CellStyle = j % 2 == 0 ? style1 : style2;
                    //根據資料型別設定不同型別的cell
                    object obj = data[i, j];
                    SetCellValue(cell, data[i, j]);
                    //如果是日期,則設定日期顯示的格式
                    if (obj.GetType() == typeof(DateTime))
                    {
                        cell.CellStyle = dateStyle;
                    }
                    //如果要根據內容自動調整列寬,需要先setCellValue再呼叫
                    //sheet.AutoSizeColumn(j);
                }
            }

            //合併單元格,如果要合併的單元格中都有資料,只會保留左上角的
            //CellRangeAddress(0, 2, 0, 0),合併0-2行,0-0列的單元格
            CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
            sheet.AddMergedRegion(region);

            try
            {
                FileStream fs = File.OpenWrite(filePath);
                wb.Write(fs);//向開啟的這個Excel檔案中寫入表單並儲存。  
                fs.Close();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }

  如果想要設定單元格為只讀或可寫,可以參考這裡,方法如下:

ICellStyle unlocked = wb.CreateCellStyle();
        unlocked.IsLocked = false;//設定該單元格為非鎖定
cell.SetCellValue("未被鎖定");
cell.CellStyle = unlocked;
...
//保護表單,password為解鎖密碼
//cell.CellStyle.IsLocked = true;的單元格將為只讀
sheet.ProtectSheet("password");

  cell.CellStyle.IsLocked預設就是true,因此sheet.ProtectSheet("password")一定要執行,才能實現鎖定單元格,對於不想鎖定的單元格,就一定要設定cellCellStyle中的IsLocked = false

  原文連結:https://www.cnblogs.com/restran/p/3889479.html

  後續會陸續更新其他資料,喜歡請關注哦!

  我的部落格:https://www.cnblogs.com/duhaoran/