APACHE POI 4.1:从十六进制代码设置单元格背景颜色

Tom*_*olo 1 java spring colors apache-poi apache-poi-4

我尝试了在堆栈溢出上发布的不同解决方案,以将背景颜色应用于 Apache POI 生成的单元格,但没有任何效果。

我正在做类似的事情:

Workbook workbook = new XSSFWorkbook(); 
Sheet sheet = workbook.createSheet(sheetName);

XSSFCellStyle cellStyle = ((XSSFCellStyle) workbook.createCellStyle());

if (styleObject.getBgColor() != null) {
    java.awt.Color javaBdgColor = java.awt.Color.decode(voceStyle.getBgColor()); // this is #FFF000
    XSSFColor bgColor = new XSSFColor(javaBdgColor, new DefaultIndexedColorMap());
    cellStyle.setFillForegroundColor(bgColor.getIndex());
    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}

Row newRow = Rowsheet.createRow(0);
Cell newCell = newRow.createCell(0);
newCell.setCellStyle(cellStyle);

// write file
String pathFileExport = buildPathExportFile("test-export");
FileOutputStream fileOut = new FileOutputStream(pathFileExport);
workbook.write(fileOut);
fileOut.close();

//close workbook
workbook.close();

return Paths.get(pathFileExport);
Run Code Online (Sandbox Code Playgroud)

我认为我的代码中一切正常,但每个单元格样式都会导致黑色背景。 黑细胞

我对没有字段的调试结果期间的“DefaultIndexedColorMap”实例有一些疑问:

代码调试器

在这一点上,我不确定该怎么做才能解决。其他帖子中的每个人似乎都能正常工作,但我的背景仍然是深色而不是黄色。

有什么建议?提前致谢!

Axe*_*ter 10

正如另一个答案所说,在自定义颜色方面,必须使用setFillForegroundColor(XSSFColor color)而不是使用索引XSSFCellStyle颜色。但是,从索引颜色使用org.apache.poi.ss.usermodel.IndexedColors是可能的XSSF了。如果不需要使用自定义颜色,这将是最兼容的方式。

但也应避免创建XSSFColorfrom java.awt.Color。构造函数XSSFColor(java.awt.Color clr, IndexedColorMap map)被标记为“仅测试”。并且java.awt.Color在某些情况下将不可用。

因此,如果需要“从十六进制代码设置单元格背景颜色”并且十六进制代码在 a 中Stringorg.apache.commons.codec.binary.Hex则可用于从中获取byte[]数组StringApache commons codec已经是apache poi的依赖项之一。然后可以使用构造函数 XSSFColor(byte[] rgb, IndexedColorMap colorMap)IndexedColorMap直到现在都没有使用。所以可以设置null。如果以后IndexedColorMap有任何使用,那么无论如何都必须调整代码。

例子:

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.commons.codec.binary.Hex;

class CreateXSSFColor {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook(); 
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   String rgbS = "FFF000";
   byte[] rgbB = Hex.decodeHex(rgbS); // get byte array from hex string
   XSSFColor color = new XSSFColor(rgbB, null); //IndexedColorMap has no usage until now. So it can be set null.

   XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
   cellStyle.setFillForegroundColor(color);
   cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

   Sheet sheet = workbook.createSheet(); 
   Row row = sheet.createRow(0);
   Cell cell = row.createCell(0);
   cell.setCellValue("yellow");
   cell.setCellStyle(cellStyle);

   workbook.write(fileout);
  }

 }
}
Run Code Online (Sandbox Code Playgroud)