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()方法只有四種重載方法,參數分別是stringboolDateTimedoubleIRichTextString
設置公式使用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://blog.csdn.net/CatchMe_439/article/details/71108386

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

  我的博客:https://www.cnblogs.com/duhaoran/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM