Java 的 Maven项目将数据库查询出的List<Object> 输出到Excel
在Java中,使用Maven项目将数据库查询结果转换为Excel文件通常涉及到两个步骤:数据获取和数据导出。首先,你需要通过JDBC或ORM框架如MyBatis从数据库查询数据,并将数据封装成List<Object>
的形式。
以下是一个基本示例,假设我们使用Apache POI库操作Excel:
添加依赖: 在pom.xml中添加Apache POI和JXL的依赖,如果还没有的话:
<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> <!-- 如果需要JDBC连接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!-- 版本号根据自己实际使用的为准 --> </dependency> </dependencies>
数据查询: 使用JDBC或ORM获取数据:
String sql = "SELECT * FROM your_table"; List<Object[]> data = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(YourObject.class)); // 使用Spring JDBC 或 MyBatis等
这里
YourObject
是你自定义的一个类,用来映射数据库表的字段。将数据写入Excel: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
// 创建一个新的Excel工作簿 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Your Sheet Name");
int rowNum = 0; for (Object[] rowData : data) { Row row = sheet.createRow(rowNum++); for (int colNum = 0; colNum < rowData.length; colNum++) { Cell cell = row.createCell(colNum); if (rowData[colNum] instanceof String) { // 根据数据类型适配设置cell值 cell.setCellValue((String)rowData[colNum]); } else if (rowData[colNum] instanceof Date) { cell.setCellValue(DateUtil.formatCellValue((Date)rowData[colNum])); } // 更多的数据类型处理... } }
// 写入文件 try (OutputStream outputStream = new FileOutputStream(new File("output.xlsx"))) { workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } ```
相关推荐


















