简体   繁体   English

编写Excel文件jdbctemplate

[英]Writing Excel file jdbctemplate

This may seem a trivial question but I am using jdbctemplate and need to export data to an excel file. 这似乎是一个琐碎的问题,但我正在使用jdbctemplate,并且需要将数据导出到excel文件。 Not sure if I can use the CSVWriter since jdbctemplate does not have a method to return a resultset and I need the headers. 不知道我是否可以使用CSVWriter,因为jdbctemplate没有返回结果集的方法,因此我需要标头。 I do not want to hardcode the headers in the code either as they will change. 我不想对代码中的标头进行硬编码,因为它们会发生变化。 I just want to dump the data as is from the db (along with headers). 我只想按原样从db(以及标头)中转储数据。

To access the metadata of a ResultSet you can use RowMapper , RowCallbackHandler or ResultSetExtractor . 要访问ResultSet的元数据,可以使用RowMapperRowCallbackHandlerResultSetExtractor To write a file for Excel you can use Apache POI . 要为Excel编写文件,可以使用Apache POI Example: 例:

Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("sheetname");
jdbcTemplate.query("select * from xyz", new RowCallbackHandler() {
    public void processRow(ResultSet rs) throws SQLException {
        String columnName = rs.getMetaData().getColumnName(column);
        String columnValue = rs.getString(column);

        Row row = sheet.createRow(sheetRow);
        row.createCell(column).setCellValue(columnValue);
    }
});

try (FileOutputStream out = new FileOutputStream(new File("export.xlsx"))) {
    workbook.write(out);
}

Check also the implementing classes of these interfaces. 还要检查这些接口的实现类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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