Export Result of Native Query to Excel JPA

In my web application I need to export MySQL Native Query result to a Excel file. I don’t know in advance how many columns I will have in query and can’t make any predefined class for it.

I searched a lot but couldn’t find anything that will export any MySQL native query result to Excel file.

Can anyone tell me how can I achieve this?

Answer

You could use apache-poi library. And your code will look like this:

public class ExcelFile {

    private final List<Object[]> data;
    private final String filePath;

    public ExcelFile(final List<Object[]> data, final String filePath) {
        this.data = data;
        this.filePath = filePath;
    }

    public void export() {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet();
            fillSheet(sheet);
            workbook.write(new FileOutputStream(filePath));
        } catch (IOException ignore) {
            ignore.printStackTrace();
        }
    }

    private void fillSheet(final XSSFSheet sheet) {
        for (int i = 0; i < data.size(); i++) {
            XSSFRow excelRow = sheet.createRow(i);
            Object[] dbRow = data.get(i);
            fillRow(excelRow, dbRow);
        }
    }

    private void fillRow(final XSSFRow row, final Object[] dbRow) {
        for (int j = 0; j < dbRow.length; j++) {
            XSSFCell cell = row.createCell(j);
            cell.setCellValue(String.valueOf(dbRow[j]));
        }
    }
}

Maven dependencies:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

Full example: here

Leave a Reply

Your email address will not be published. Required fields are marked *