i为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颜色都是一样的?我不明白我做错了什么。谢谢。
您基本上将表的组件的背景颜色复制到Excel;您需要调试/找出哪种颜色。
我认为它们都是相同的颜色 - 这就是为什么您在Excel中获得SME颜色。
如果 - 例如 - 您更改
Color color = c.getBackground() != null ? c.getBackground() : table.getBackground();
to
Color color = (i % 2 == 0 ? Color.RED : Color.BLUE);
您会得到红色和蓝色行的混合物 - 因此您的代码确实可以使用。基本上,您需要检查哪种颜色进入CreateNewcolorCellstyle,然后以一种或另一种方式更改该颜色。
另外,在setColor中,您两次定义hssfcolor;在行中
HSSFColor hssfColor = palette.getColor(HSSFColor.BLUE_GREY.index);
您需要删除声明hssfcolor。