EduBw
EduBw

Reputation: 942

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.

Upvotes: 0

Views: 193

Answers (1)

Florian Kling
Florian Kling

Reputation: 155

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

Upvotes: 2

Related Questions