我尝试了在堆栈溢出上发布的不同解决方案,以将背景颜色应用于 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);
我认为我的代码中的一切都很好,但每个像这样设置样式的单元格都会导致黑色背景。
我对在没有字段的调试结果期间的“DefaultIndexedColorMap”实例有一些疑问:
在这一点上,我不确定该怎么做才能解决。 其他帖子中的每个人似乎都能正常工作,但我的背景仍然是深色而不是黄色。
有什么建议吗? 提前致谢!
最佳答案
正如另一个答案所说,setFillForegroundColor(XSSFColor color) 的用法当涉及到自定义颜色时,XSSFCellStyle
中有必要代替使用索引颜色。但是使用 org.apache.poi.ss.usermodel.IndexedColors 中的索引颜色在 XSSF
中也是可能的。如果不需要使用自定义颜色,这将是最兼容的方式。
但也应避免从 java.awt.Color
创建 XSSFColor
。构造函数XSSFColor(java.awt.Color clr, IndexedColorMap map)标记为“仅测试”。并且 java.awt.Color
在某些情况下将不可用。
所以如果需要“从十六进制代码设置单元格背景颜色”并且十六进制代码在 String
中,那么 org.apache.commons.codec.binary.Hex
可用于从 String
获取 byte[]
数组。 Apache 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);
}
}
}
关于java - APACHE POI 4.1 : Set cell background color from hex code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58594849/