我尝试了发布在堆栈溢出上的不同解决方案,以将背景颜色应用于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“实例有一些怀疑:
在这一点上,我不确定要做什么来解决。其他帖子中的每个人似乎都能让事情正常工作,但我的背景仍然是深色而不是黄色。
有什么建议吗?提前感谢!
发布于 2019-10-29 15:45:29
正如另一个答案所说,在XSSFCellStyle
中,当涉及到自定义颜色时,使用setFillForegroundColor(XSSFColor color)而不是使用索引颜色是必要的。但是在XSSF
中也可以使用org.apache.poi.ss.usermodel.IndexedColors中的索引颜色。如果不需要使用定制的颜色,这将是最兼容的方式。
但也应该避免从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);
}
}
}
发布于 2019-10-29 01:46:42
我注意到,在处理xlsx文件(XSSF)中的颜色时,使用索引颜色效果不是很好。默认情况下,XSSFWorkbook
中的任何颜色似乎都没有索引,因此您不能使用没有索引的颜色索引。
但是,您可以使用overload of setFillForegroundColor
that directly takes an XSSFColor
。
cellStyle.setFillForegroundColor(bgColor);
当我使用这个重载时,我会得到黄色作为你所期望的背景。
通常,在XSSF中处理颜色时,应该使用XSSFColor
本身,而不是它的索引。这适用于其他颜色,如其他图案颜色(“背景”)、边框颜色和字体颜色。
https://stackoverflow.com/questions/58594849
复制相似问题