[C#] NPOI 儲存格文字顏色

2018-08-07

之前分享過這這篇文章 透過NPOI 產生 Excel 檔案 (*.xls) ,最近因為要處理有要對帳的東西,需要在 文件中儲存格顯示不同顏色,所以就重新看了一下自己的文章,網路上也查了一下,可能是因為版本關係竟然有些寫得跑起來不是沒變化,就是整個文件都變色,所以就寫一篇記錄一下

Image130

現在我用的版本是 2.3


其中,如果你沒有玩過這東西,你可以參考我這篇文章 透過NPOI 產生 Excel 檔案 (*.xls) ,其中,我是修改這個的範例,首先,我們要先設定兩種 style 一個是綠色,一個是紅色的字

//綠色的Style NPOI.SS.UserModel.IFont fontG = workbook.CreateFont(); fontG.Color = NPOI.SS.UserModel.IndexedColors.Green.Index; var styleG = workbook.CreateCellStyle(); styleG.SetFont(fontG); //紅色的Style NPOI.SS.UserModel.IFont fontR = workbook.CreateFont(); fontR.Color = NPOI.SS.UserModel.IndexedColors.Red.Index; var styleR = workbook.CreateCellStyle(); styleR.SetFont(fontR);

之後根據之前的範例,我們為了區分,我讓迴圈裏面,如果==5 就是紅色,如果==10 就是綠色的字,其他就是不去改變。

for (var i = 1; i <= 20; i++) { sheetReportResult.CreateRow(i).CreateCell(0).SetCellValue("用戶" + i); if (i== 5) { var cell = sheetReportResult.GetRow(i).CreateCell(1); cell.CellStyle = styleR; cell.SetCellValue("091234567" + i); } else if (i == 10) { var cell = sheetReportResult.GetRow(i).CreateCell(1); cell.CellStyle = styleG; cell.SetCellValue("091234567" + i); } else { var cell = sheetReportResult.GetRow(i).CreateCell(1); cell.SetCellValue("091234567" + i); } sheetReportResult.GetRow(i).CreateCell(2).SetCellValue("我是備註" + i); }

結果:

Image132

完整程式碼:

var workbook = new HSSFWorkbook(); var sheetReportResult = workbook.CreateSheet("報表結果"); //綠色的Style NPOI.SS.UserModel.IFont fontG = workbook.CreateFont(); fontG.Color = NPOI.SS.UserModel.IndexedColors.Green.Index; var styleG = workbook.CreateCellStyle(); styleG.SetFont(fontG); //紅色的Style NPOI.SS.UserModel.IFont fontR = workbook.CreateFont(); fontR.Color = NPOI.SS.UserModel.IndexedColors.Red.Index; var styleR = workbook.CreateCellStyle(); styleR.SetFont(fontR); //產生第一個要用CreateRow sheetReportResult.CreateRow(0).CreateCell(0).SetCellValue("姓名"); //之後的用GetRow 取得在CreateCell sheetReportResult.GetRow(0).CreateCell(1).SetCellValue("電話"); sheetReportResult.GetRow(0).CreateCell(2).SetCellValue("備註"); //第一Row 已經被Title用掉了 所以從1開始 for (var i = 1; i <= 20; i++) { sheetReportResult.CreateRow(i).CreateCell(0).SetCellValue("用戶" + i); if (i== 5) { var cell = sheetReportResult.GetRow(i).CreateCell(1); cell.CellStyle = styleR; cell.SetCellValue("091234567" + i); } else if (i == 10) { var cell = sheetReportResult.GetRow(i).CreateCell(1); cell.CellStyle = styleG; cell.SetCellValue("091234567" + i); } else { var cell = sheetReportResult.GetRow(i).CreateCell(1); cell.SetCellValue("091234567" + i); } sheetReportResult.GetRow(i).CreateCell(2).SetCellValue("我是備註" + i); } sheetReportResult.SetColumnWidth(0, 20 * 256); sheetReportResult.SetColumnWidth(1, 40 * 256); sheetReportResult.SetColumnWidth(2, 40 * 256); var file = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "sample.xls", FileMode.Create); workbook.Write(file); file.Close();


當麻許的碎念筆記 2014 | Donma Hsu Design.