問題
想針對欄位設定背景,但對CellStyle的屬性FillBackgroundColor指定了顏色之後,卻沒有反應,大致程式碼如下
var sheet = workbook.GetSheet("test");
var rowEnum = sheet.GetRowEnumerator();
while (rowEnum.MoveNext())
{
XSSFCellStyle customStyle = (XSSFCellStyle)workbook.CreateCellStyle();
customStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.LightYellow.Index;
for (int i = 0; i < row.Cells.Count; i++)
{
ICell cell = row.Cells[i];
if (i >= 2)
{
customStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,##0");
}
cell.CellStyle = customStyle;
}
}解法
- 將屬性
FillBackgroundColor改為FillForegroundColor - 設定
FillPattern屬性為FillPattern.SolidForeground
var sheet = workbook.GetSheet("test");
var rowEnum = sheet.GetRowEnumerator();
while (rowEnum.MoveNext())
{
XSSFCellStyle customStyle = (XSSFCellStyle)workbook.CreateCellStyle();
customStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightYellow.Index;
customStyle.FillPattern = FillPattern.SolidForeground;
for (int i = 0; i < row.Cells.Count; i++)
{
ICell cell = row.Cells[i];
if (i >= 2)
{
customStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,##0");
}
cell.CellStyle = customStyle;
}
}說明
根據網友的說法,填滿在Excel裡面是兩種顏色前景色及背景色,且你還必須要指定樣式為填滿樣式(FillPattern),但填滿樣式只有前景,即SolidForeground,也就是說要將自己以為的”背景色”,改為指定前景色(ForegroundColor),這真的是很不科學。
題外話
如果設定customStyle.FillBackgroundColor然後設定customStyle.FillPattern = FillPattern.SolidForeground會發生什麼事情?
實驗結果,因為沒有指定前景色,所以它會變成黑色背景。



