SpringBoot导出Excel模板
共同探讨,向各位大佬学习
走向CEO,迎娶白富美
pom.xml依赖
<!--excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
Excel模板文件
在项目resources包下创建templates,将准备好的模板文件放在templates包下。
Controller
@GetMapping("/report")
public void report(HttpServletResponse response){
try {
//从数据库获取数据
List<User> userList = userMapper.selectList(null);
//获取Excel模板文件绝对磁盘路径
String path = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "templates/user.xlsx").getPath();
//基于POI在内存中创建一个Excel文件
XSSFWorkbook excel= new XSSFWorkbook(new FileInputStream(new File(path)));
//获取第一个工作表
XSSFSheet sheet = excel.getSheetAt(0);
//设置行变量
int firstNum = 0;
//遍历集合
for (User user : userList) {
//从第二行开始创建新行
XSSFRow row = sheet.createRow(++firstNum);
//创建新列,并设值
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getPassword());
row.createCell(2).setCellValue(user.getAge());
row.createCell(3).setCellValue(user.getSex());
}
//创建输出流,用于从服务器写数据到客户端浏览器
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("content-Disposition", "attachment;filename=user.xlsx");
excel.write(out);
//关闭流
out.flush();
out.close();
excel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
测试
———————————————————————————————————————