1、maven工程引入POI包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2、查询数据写入文件
public void exportExcel() {
List<User> users = iDao.selectUser(new HashMap<>());
if (null != users && 0 < users.size()){
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("第一个工作表");
Row titleRow=sheet.createRow(0);
titleRow.createCell(0).setCellValue("主键");
titleRow.createCell(1).setCellValue("用户名");
titleRow.createCell(2).setCellValue("密码");
titleRow.createCell(3).setCellValue("邮箱");
for (int i = 0; i < users.size(); i++) {
Row row=sheet.createRow(i+1);
row.createCell(0).setCellValue(users.get(i).getUserId());
row.createCell(1).setCellValue(users.get(i).getUserName());
row.createCell(2).setCellValue(users.get(i).getUserPassword());
row.createCell(3).setCellValue(users.get(i).getUserEmail());
}
String path = "D://exportExcel.xlsx";
FileOutputStream fos=null;
try {
fos = new FileOutputStream(path);
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、运行结果
主键 | 用户名 | 密码 | 邮箱 |
---|
1 | 唐三 | tangsan | tangsan@qq.com |
2 | 小舞 | xiaowu | xiaowu@qq.com |
3 | 大明 | daming | daming@qq.com |
4 | 二明 | erming | erming@qq.com |