赞
踩
在pom.xml文件中添加如下两个包:
<!-- 后端常用java类库 Hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M3<ersion>
</dependency>
<!-- poi 导出excel需要用到-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2<ersion>
</dependency>
以下以用户信息导入导出为例,在UserController中实现代码如下:
(1)导入Excel表格
//导入Excel
@PostMapping("/import")
public R<?> importExcel(MultipartFile file) throws Exception {
InputStream inputStream = file.getInputStream();
ExcelReader reader = ExcelUtil.getReader(inputStream);
List<User> list = reader.readAll(User.class);
System.out.println(list);
return userService.saveBatch(list);
// return R.success();
}
(2)导出Excel表格
//导出Excel @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws Exception { //从数据库查询出所有的数据 List list = userService.findAll(); // 通过工具类创建writer 写出到磁盘路径 // ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath +"/用户信息..xlsX"); // 在内存操作,写出到浏览器 ExcelWriter writer = ExcelUtil.getWriter(true); // writer.setOnlyAlias(true); // // 自定义标题别名 // writer.addHeaderAlias( "id" ,"ID"); //一次性写出list内的对象到excel,使用默认样式,强制输出标题 writer.write(list, true); response.setContentType("applicationnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); String fileName = URLEncoder.encode( "用户信息", StandardCharsets.UTF_8); response.setHeader( "Content-Disposition","attachment;filename=" + fileName + ".xlsx"); ServletOutputStream out = response.getOutputStream(); writer.flush(out,true); out.close(); writer.close(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。