我尝试过在堆栈溢出上发布的其他解决方案,将背景色应用于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
了。如果不需要使用自定义颜色,这将是最兼容的方式。
但也应避免创建“ XSSFColor
from” java.awt.Color
。构造函数XSSFColor(java.awt.Color clr,IndexedColorMap地图)标记为“仅测试”。并且java.awt.Color
在某些情况下将不可用。
因此,如果需要“从十六进制代码设置单元格背景颜色”并且该十六进制代码在中String
,则org.apache.commons.codec.binary.Hex
可以用来从中获取byte[]
数组String
。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);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句