我在加入样式和字体时遇到问题。最后当我创建excel时,excel创建成功,但是我的excel没有样式和字体,他什么都没有,只有数据,我需要背景颜色:行== 0中的红色和颜色纯白色
我的代码:
try {
String filename = pathTempdownloadFile;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(eyelash);
CellStyle backgroundStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
backgroundStyle.setFillBackgroundColor(IndexedColors.RED.getIndex());
font.setColor(IndexedColors.WHITE.getIndex());
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("YEAR");
rowhead.createCell(1).setCellValue("MONTH");
rowhead.createCell(2).setCellValue("NAME)");
rowhead.createCell(3).setCellValue("SURNAME");
rowhead.setRowStyle(backgroundStyle);
backgroundStyle.setFont(font);
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
workbook.close();
} catch (Exception ex) {
System.out.println(ex);
}
重复:我可以用数据创建 Excel,但我的 Excel 没有样式,也没有字体。
最佳答案
这应该有效:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.WHITE.index);
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.RED.index);
List<String> header = Arrays.asList(new String [] {"YEAR", "MONTH", "NAME", "SURNAME"});
HSSFRow rowhead = sheet.createRow((short) 0);
int cellnum = 0;
for (String s : header) {
HSSFCell cell = rowhead.createCell(cellnum++);
cell.setCellValue(s);
cell.setCellStyle(style);
}
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
workbook.close();
关于Java 用样式创建 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51416267/