我为 HSSFWorkbook 创建单元格样式:
private static HSSFCellStyle createNewColorCellStyle(Map<Color, HSSFCellStyle> cellStylesMap, HSSFWorkbook workbook, Color color) {
if (cellStylesMap.get(color) == null) {
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFColor hssfColor = setColor(workbook, (byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue());
cellStyle.setFillForegroundColor(hssfColor.getIndex());
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setBorderTop(CellStyle.BORDER_THIN);
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
cellStyle.setBorderRight(CellStyle.BORDER_THIN);
cellStylesMap.put(color, cellStyle);
}
return cellStylesMap.get(color);
}
有我将颜色设置为单元格样式的功能
private static HSSFColor setColor(HSSFWorkbook workbook, byte r, byte g, byte b) {
HSSFPalette palette = workbook.getCustomPalette();
HSSFColor hssfColor = null;
try {
hssfColor = palette.findColor(r, g, b);
if (hssfColor == null) {
palette.setColorAtIndex(HSSFColor.BLUE_GREY.index, r, g, b);
HSSFColor hssfColor = palette.getColor(HSSFColor.BLUE_GREY.index);
}
} catch (Exception e) {
LOGGER.info(String.valueOf(e));
}
return hssfColor;
}
我在那个方法中使用它,我将我的样式设置为 HSSFCell。使用我的地图样式的功能。我在循环中创建行和单元格:
void excell(Path path, JTable table) {
try {
HSSFWorkbook fWorkbook = new HSSFWorkbook();
HSSFSheet fSheet = fWorkbook.createSheet("the sheet");
Map<Color, HSSFCellStyle> cellStylesMap = new HashMap<>();
TableModel model = table.getModel();
for (int i = 0; i < model.getRowCount(); i++) {
HSSFRow fRow = fSheet.createRow((short) i);
for (int j = 0; j < table.getColumnModel().getColumnCount(); j++) {
HSSFCell cell = fRow.createCell(j);
cell.setCellValue(model.getValueAt(i, j));
Component c = table.getCellRenderer(i, j).getTableCellRendererComponent(table, cell, table.isCellSelected(i, j), table.hasFocus(), i, j);
Color color = c.getBackground() != null ? c.getBackground() : table.getBackground();
cell.setCellStyle(createNewColorCellStyle(cellStylesMap, fWorkbook, color));
}
}
}
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(path.toString());
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
fWorkbook.write(bos);
bos.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我所有的细胞都是一种颜色。在不同的机器上有不同的颜色。有什么错误?为什么我所有的excel颜色都一样?我不明白我做错了什么。谢谢。