Search code examples
javaexcelgrailsgroovyapache-poi

Grails: Excel exporting .xlsx style issues, error message when opening the file


I'm using grails-excel-export plugin to export data into an Excel (in xlsx format), but I'm having issues when opening the file with Microsoft Office (no problems with OpenOffice).

When I open it, I get the message "We found a problem with some of the content in 'exportedFile.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes", same as this one:

enter image description here

I've already found out that the problem comes only when applying any kind of cellstyle to the workbook, in my case I'm to set bold the first row.

This is the code:

def exportToExcel(results, headers, properties, ByteArrayOutputStream outputStream) {

    WebXlsxExporter webXlsxExporter = new WebXlsxExporter()
    webXlsxExporter.setWorksheetName("Sheet")
    webXlsxExporter.with {
        fillHeader(headers)
        add(results, properties)
        save(outputStream)
    }

    def wb = webXlsxExporter.getWorkbook()
    def row = webXlsxExporter.getSheet().getRow(0)
    makeFirstRowBold(wb, row)

    wb.write(outputStream)
}

def makeFirstRowBold(Workbook wb, Row row) {
    CellStyle style = wb.createCellStyle()
    Font font = wb.createFont()
    font.setBold(true) //Already tried with font.setBoldweight(Font.BOLDWEIGHT_BOLD)
    style.setFont(font)

    for (int i = 0; i < row.getLastCellNum(); i++) {
        row.getCell(i).setCellStyle(style)
    }
}

Solution

  • In case this happens to anyone else, turns out that writing twice to outputstream was somehow corrupting the file.

    So, since we are already writing to the outputstream in this line:

    wb.write(outputStream)
    

    I removed this one:

    save(outputStream)
    

    And it seems to be working fine.