【发布时间】:2018-11-09 14:00:02
【问题描述】:
org.apache.poi 4.0 删除了仅使用 java.awt.Color 的 XSSFColor 构造函数。在org.apache.poi 3.7 中,只需编写即可轻松创建对象
Color inputColor = Color.RED;
XSSFColor test = new XSSFColor(inputColor);
但是,此构造函数在 4.0 中不再有效。 https://poi.apache.org/apidocs/dev/org/apache/poi/xssf/usermodel/XSSFColor.html 的文档显示了其他几个构造函数,但理想情况下,我希望更改尽可能少的行。
所以,我的问题是,现在从 java.awt.Color 创建 XSSFColor 的最佳方法是什么(在 apache poi 4.0 中)?
根据 cmets 的要求,这是我使用建议 style.setFillForegroundColor(new XSSFColor(java.awt.Color.RED, null)); 的测试代码
使用 LibreOffice 6.1 打开它会产生错误(尝试修复,然后失败)。注释掉可以正常工作的POI 3.7版本。
@Test
public void testPOI40() throws FileNotFoundException, IOException {
Workbook workbook = new XSSFWorkbook();
XSSFSheet fSheet = (XSSFSheet) workbook.createSheet("new Sheet");
XSSFRow hRow = fSheet.createRow((short) 0);
//header
String[] astrHeaders = new String[]{"Header1", "Header2", "Header3", "Header4"};
for (int col = 0; col < astrHeaders.length; col++) {
XSSFCell cell = hRow.createCell((short) col);
XSSFCellStyle tempHeaderStyle = (XSSFCellStyle) workbook.createCellStyle();
tempHeaderStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
tempHeaderStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellValue(astrHeaders[col]);
cell.setCellStyle(tempHeaderStyle);
}
//body
Double[] astrContent = new Double[]{1.3, 0.3, 0.87, 1.0};
Color[] colors = new Color[] {Color.RED,Color.BLUE,Color.WHITE,Color.GREEN};
XSSFRow fRow = fSheet.createRow((short) 1);
for (int iCol = 0; iCol < 4; iCol++) {
XSSFCell cell = fRow.createCell((short) iCol);
XSSFCellStyle tempBodyStyle = (XSSFCellStyle) workbook.createCellStyle();
cell.setCellValue(astrContent[iCol]);
//working with POI 3.17
//tempBodyStyle.setFillForegroundColor(new XSSFColor(colors[iCol]));
tempBodyStyle.setFillForegroundColor(new XSSFColor(colors[iCol],null));
tempBodyStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(tempBodyStyle);
}
FileOutputStream fileOut = new FileOutputStream(new File("testfile.xlsx"));
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
workbook.write(bos);
fileOut.close();
}
解决方案:
将fileout.close(); 替换为bos.close(); 并且可以正常工作。所以 tempBodyStyle.setFillForegroundColor(new XSSFColor(Color.RED,null)); Alex Richter 在 cmets 中的建议是一个很好的解决方案,并且会接受这个作为答案。
【问题讨论】:
-
感谢您的回答,但是第一种方法生成的表格在尝试打开时报告为损坏。第二种方法失败,因为
setColor(Color) has protected access in ExtendedColor。 -
抱歉,
style.setFillForegroundColor(new XSSFColor(java.awt.Color.RED, null));对我有用,使用apache poi 4.0.0并从头开始创建XSSFWorkbook。请显示最小的完整可验证示例,说明失败的地方。 -
谢谢您,我现在将您的建议的测试添加到主帖中。
-
澄清一下,代码不会导致错误,但是输出文件无法读取(但是使用 POI 3.7 的版本,见注释掉的部分,是可读的)
-
损坏与颜色无关。您将 FileOutputStream 包装在 BufferedOutputStream 中,但只关闭内部 FileOutputStream 而不是 BufferedOutputStream。做
workbook.write(bos); bos.close();,它会起作用的。至少它对我有用。它可能在以前的apache poi版本中工作,因为Workbook.write在准备好时关闭了所有流。这没有更多。
标签: java colors apache-poi apache-poi-4