简体   繁体   中英

Java create Excel with styles

I have problems when I join the styles and fonts. Finally when I created the excel, the excel create success, but my excel doesn't have style and font, he doesn't have nothing, only datas , I need background-color: red and color-solid white in row == 0

My code:

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);
}

Repeat : I can create the excel with data, but My excel doesn't have style neither font.

This should work:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM