1. 程式人生 > >C# NPOI 修改指定單元格的樣式 或者行樣式

C# NPOI 修改指定單元格的樣式 或者行樣式

#region 2.NPOI讀取Excel 驗證Excel資料的有效性(非空) 並修改指定單元格樣式
            IWorkbook workbook = null;
            ISheet sheet = null;
            ArrayList questionRowIndex = new ArrayList();/*收集出現問題行的索引*/


            using (FileStream fs = System.IO.File.Open(readExcelPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            { 
                #region 選擇解析方式
                if (dataLog.ExcelName.IndexOf(".xlsx") > 0)
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if(dataLog.ExcelName.IndexOf(".xls") > 0)
                {
                    workbook = new HSSFWorkbook(fs);
                }
                #endregion


                #region 核驗數值列資料是否為空 並記錄為空索引行 修改Excel指定索引行後重新儲存


                sheet = workbook.GetSheetAt(0);/*指定資料格式只讀取索引值為0的第一個sheet*/
                IRow row = null;                
                for(int j =1;j < sheet.PhysicalNumberOfRows && sheet.GetRow(j) != null;j++)/*j=1 從索引的第一行開始過濾掉表頭*/
                {
                    row = sheet.GetRow(j);
                    if (string.IsNullOrWhiteSpace(row.GetCell(5).ToString()))/*驗證數值非空*/
                    {                      

                        questionRowIndex.Add(j);

                        /*修改樣式關鍵程式碼*/
                        ICellStyle style = workbook.CreateCellStyle();
                        style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;
                        style.FillPattern = FillPattern.SolidForeground;

                        style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;

/*修改指定單元格樣式 如果要修改行樣式則需要將row.Cells.Count迴圈出來,挨個設定!*/

                        row.Cells[5].CellStyle = style;

//for(int i=0;i<row.Cells.Count;i++)

//{

//row.Cells[i].CellStyle = style;

//}



                        /*重新修改檔案指定單元格樣式*/
                        FileStream fs1 = System.IO.File.OpenWrite(readExcelPath);
                        workbook.Write(fs1);
                        fs1.Close();          
             
                    }
                }
                #endregion
            }