2014-12-05 96 views
4

我在C#項目中使用NPOI 2.0.6.0,我遇到了更改樣式的困難。 雖然我可以影響字體和單元格邊框,但我無法更改背景顏色。無法設置FillBackgroundColor

private void buildSheet(HSSFWorkbook wb, DataTable data, string sheetName) 
{ 
    var cHelp = wb.GetCreationHelper(); 
    var sheet = wb.CreateSheet(sheetName); 

    HSSFFont hFont = (HSSFFont)wb.CreateFont(); 

    hFont.Boldweight = (short)FontBoldWeight.Bold; 
    hFont.Color = HSSFColor.White.Index; 
    hFont.FontHeightInPoints = 18; 

    HSSFCellStyle hStyle = (HSSFCellStyle)wb.CreateCellStyle(); 
    hStyle.SetFont(hFont); 
    hStyle.BorderBottom = BorderStyle.Medium; 
    hStyle.FillBackgroundColor = HSSFColor.Black.Index; 

    IRow headerRow = sheet.CreateRow(1); 


    int cellCount = 1; 
    foreach (string str in colHeaders) 
    { 
     HSSFCell cell = (HSSFCell)headerRow.CreateCell(cellCount); 
     cell.SetCellValue(cHelp.CreateRichTextString((str))); 
     cell.CellStyle = hStyle; 

     cellCount += 1; 
    } 

    int rowCount = 2; 
    foreach (DataRow dr in data.Rows) 
    { 
     var row = sheet.CreateRow(rowCount); 
     for (int i = 1; i < data.Columns.Count + 1; i++) 
     { 
      row.CreateCell(i).SetCellValue(cHelp.CreateRichTextString((dr[i - 1]).ToString())); 
     } 
     rowCount += 1; 
    } 
} 

安裝調試後,我注意到,hStyle.FillBackgroundColor從不即0x0040儘管黑色的指數爲8。

所以基本上的問題是改變:

  • 爲什麼會HSSFCellStyle.FillBackgroundColor不可以修改嗎?

回答

13

如果沒有指定FillPattern,則不能應用FillBackgroundcolor

 hStyle = (HSSFCellStyle)workBook.CreateCellStyle(); 
     hStyle.SetFont(xFont); 
     hStyle.BorderBottom = BorderStyle.Medium; 
     hStyle.FillForegroundColor = IndexedColors.Black.Index; 
     hStyle.FillPattern = FillPattern.SolidForeground; 
+2

你的答案設置前景。問題是關於BACK的問題。我遵循你所說的並獲得了黑色單元格,即使我將「背景」更改爲「黃色」。如果將FillPattern更改爲FillPattern.LeastDots,我只能看到黃色背景,這非常煩人!任何其他人去線索 – GregJF 2015-05-26 00:47:26

+3

@GregJF請參閱:http://stackoverflow.com/questions/2803841/setting-foreground-color-for-hssfcellstyle-is-always-coming-out-black – GamerJ5 2015-05-27 02:14:02