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


參考文章:原文鏈接:https://blog.csdn.net/chensirbbk/article/details/52189985

#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
}

 

實踐代碼:

 private byte[] GetMonthBudgetInfoReport(List<MonthBudgetResponse> list)
        {
            try
            {

                string modelExlPath = Directory.GetCurrentDirectory() + "\\Template\\Equipment\\EquipmentMonthBudget.xlsx";
                if (System.IO.File.Exists(modelExlPath) == false)//模板不存在
                {
                    modelExlPath = AppContext.BaseDirectory + "Template\\Equipment\\EquipmentMonthBudget.xlsx";
                    if (System.IO.File.Exists(modelExlPath) == false)//模板不存在
                    {
                        throw new FriendlyException("未找到模板");
                    }
                }
                IWorkbook workBook = null;
                using (FileStream file = new FileStream(modelExlPath, FileMode.Open, FileAccess.Read))
                {
                    workBook = new XSSFWorkbook(file);
                    file.Close();
                }

                XSSFSheet sheet = (XSSFSheet)workBook.GetSheetAt(0);



                //特定單元格樣式 右對齊
                ICellStyle cellstyle = workBook.CreateCellStyle();
                cellstyle.Alignment = HorizontalAlignment.Right;
                cellstyle.BorderTop = BorderStyle.Thin;
                cellstyle.BorderBottom = BorderStyle.Thin;
                cellstyle.BorderLeft = BorderStyle.Thin;
                cellstyle.BorderRight = BorderStyle.Thin;

                //設置所有單元格統一的樣式  添加邊框線
                ICellStyle allcellstyle = workBook.CreateCellStyle();
                allcellstyle.BorderTop = BorderStyle.Thin;
                allcellstyle.BorderBottom = BorderStyle.Thin;
                allcellstyle.BorderLeft = BorderStyle.Thin;
                allcellstyle.BorderRight = BorderStyle.Thin;



                var rowIndex = 1;
                var cellIndex = 0;
                if (list != null && list.Count > 0)
                {
                    list.ForEach(x =>
                    {
                        IRow row = sheet.CreateRow(rowIndex);
                        row.HeightInPoints = 10 * 2;
                        row.CreateCell(cellIndex++).SetCellValue(x.ProjectName);
                        row.CreateCell(cellIndex++).SetCellValue(x.BudgetMonth.Value.ToString("yyyy-MM"));
                        row.CreateCell(cellIndex++).SetCellValue(x.TotalBuildAera.ToString());
                        row.CreateCell(cellIndex++).SetCellValue(x.BuildAera.ToString());
                        row.CreateCell(cellIndex++).SetCellValue(String.Format("{0:N2}", x.TotalBudget.Value));
                        row.CreateCell(cellIndex++).SetCellValue(String.Format("{0:N2}", x.MonthBudget.Value));

                        rowIndex++;
                        cellIndex = 0;
                    });
                }

                #region 設置單元格樣式 
                //
                for (int i = 1; i <= list.Count; i++)
                {
                    //
                    for (int j = 0; j < 6; j++)
                    {

                        sheet.GetRow(i).Cells[j].CellStyle = allcellstyle;
                    }
                }


                //設置單元格樣式
                for (int i = 1; i <= list.Count; i++)
                {
                    sheet.GetRow(i).Cells[2].CellStyle = cellstyle;
                    sheet.GetRow(i).Cells[3].CellStyle = cellstyle;
                    sheet.GetRow(i).Cells[4].CellStyle = cellstyle;
                    sheet.GetRow(i).Cells[5].CellStyle = cellstyle;
                }

                #endregion

                MemoryStream ms = new MemoryStream();
                workBook.Write(ms);
                return ms.ToArray();

            }
            catch (Exception ex)
            {
                throw new FriendlyException("導出數據失敗");
            }
        }

 https://blog.csdn.net/qq_39541254/article/details/107935095


免責聲明!

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



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