Java 用样式创建 Excel

标签 java excel

我在加入样式和字体时遇到问题。最后当我创建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/

相关文章:

vba - 打开工作簿的上次修改日期

excel - 在 Excel 应用程序中创建 Outlook 项目会生成错误 : "Object doesn' t support this property or method"

excel - 引用工作表中框架中的控件

javascript - excel可以根据网站的变量填写某些字段吗?

java - 在netty中的单例类中使用threadlocal

java - Spring Boot未加载@ConfigurationProperties

java - 将 EL 解析器与 WELD 结合使用时,如何解决类型差异?

java - JPA 标准 API : Aggregating on Multiple Columns with IF Condition

java - 线程 "main"java.lang.StackOverflowError actionListeners 中出现异常

excel - 如何根据条件删除 Excel 工作表中的行