easyPOI基本用法详解

x33g5p2x  于2021-12-18 转载在 其他  
字(36.1k)|赞(0)|评价(0)|浏览(896)

easyPOI基本用法

参考网址:http://www.wupaas.com/

1.Excel文件的简单导入和导出

项目源码:https://github.com/zhongyushi-git/springboot-easypoi.git。后台在easypoi-demo-admin目录下,前端在easypoi-demo目录下。

!!!说明:源码中可能与下面的介绍的代码稍有差异,请以源码为准。

1.1准备工作

1)首先新建一个SpringBoot的项目,搭建基本的环境访问数据,详见源码。

2)导入easypoi依赖

定义版本

  1. <easypoi.version>4.1.0</easypoi.version>

坐标:这里是以springmvc的坐标导入的,适用大部分功能。如果需求不多,可以直接导入springboot对应的坐标,二者选一。选择依据就是如果报错,就换另一种坐标即可。

  1. <!--easypoi-->
  2. <dependency>
  3. <groupId>cn.afterturn</groupId>
  4. <artifactId>easypoi-base</artifactId>
  5. <version>${easypoi.version}</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>cn.afterturn</groupId>
  9. <artifactId>easypoi-web</artifactId>
  10. <version>${easypoi.version}</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>cn.afterturn</groupId>
  14. <artifactId>easypoi-annotation</artifactId>
  15. <version>${easypoi.version}</version>
  16. </dependency>

springboot的坐标

  1. <dependency>
  2. <groupId>cn.afterturn</groupId>
  3. <artifactId>easypoi-spring-boot-starter</artifactId>
  4. <version>3.3.0</version>
  5. </dependency>

3)创建Excel操作的工具类ExcelUtils

  1. package com.example.easypoidemoadmin.utils;
  2. import cn.afterturn.easypoi.cache.manager.POICacheManager;
  3. import cn.afterturn.easypoi.excel.ExcelExportUtil;
  4. import cn.afterturn.easypoi.excel.ExcelImportUtil;
  5. import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
  6. import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
  7. import cn.afterturn.easypoi.excel.entity.ExportParams;
  8. import cn.afterturn.easypoi.excel.entity.ImportParams;
  9. import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
  10. import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
  11. import cn.afterturn.easypoi.word.WordExportUtil;
  12. import cn.afterturn.easypoi.word.parse.ParseWord07;
  13. import org.apache.commons.lang3.StringUtils;
  14. import org.apache.poi.ss.usermodel.Workbook;
  15. import org.apache.poi.ss.usermodel.WorkbookFactory;
  16. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  17. import org.springframework.web.multipart.MultipartFile;
  18. import javax.servlet.http.HttpServletResponse;
  19. import java.io.File;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.net.URLEncoder;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.NoSuchElementException;
  27. /** * Excel导入导出工具类 */
  28. public class ExcelUtils {
  29. /** * excel 导出 * * @param list 数据列表 * @param fileName 导出时的excel名称 * @param response */
  30. public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
  31. defaultExport(list, fileName, response);
  32. }
  33. /** * 默认的 excel 导出 * * @param list 数据列表 * @param fileName 导出时的excel名称 * @param response */
  34. private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
  35. //把数据添加到excel表格中
  36. Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
  37. downLoadExcel(fileName, response, workbook);
  38. }
  39. /** * excel 导出 * * @param list 数据列表 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param response * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型) */
  40. private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
  41. //把数据添加到excel表格中
  42. Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
  43. downLoadExcel(fileName, response, workbook);
  44. }
  45. /** * excel 导出 * * @param list 数据列表 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型) * @param response */
  46. public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
  47. defaultExport(list, pojoClass, fileName, response, exportParams);
  48. }
  49. /** * excel 导出 * * @param list 数据列表 * @param title 表格内数据标题 * @param sheetName sheet名称 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param response */
  50. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
  51. defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
  52. }
  53. /** * excel 导出 * * @param list 数据列表 * @param title 表格内数据标题 * @param sheetName sheet名称 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param isCreateHeader 是否创建表头 * @param response */
  54. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
  55. ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
  56. exportParams.setCreateHeadRows(isCreateHeader);
  57. defaultExport(list, pojoClass, fileName, response, exportParams);
  58. }
  59. /** * excel下载 * * @param fileName 下载时的文件名称 * @param response * @param workbook excel数据 */
  60. private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
  61. try {
  62. response.setCharacterEncoding("UTF-8");
  63. response.setHeader("content-Type", "application/vnd.ms-excel");
  64. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
  65. workbook.write(response.getOutputStream());
  66. } catch (Exception e) {
  67. throw new IOException(e.getMessage());
  68. }
  69. }
  70. /** * excel 导入 * * @param file excel文件 * @param pojoClass pojo类型 * @param <T> * @return */
  71. public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
  72. return importExcel(file, 1, 1, pojoClass);
  73. }
  74. /** * excel 导入 * * @param filePath excel文件路径 * @param titleRows 表格内数据标题行 * @param headerRows 表头行 * @param pojoClass pojo类型 * @param <T> * @return */
  75. public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
  76. if (StringUtils.isBlank(filePath)) {
  77. return null;
  78. }
  79. ImportParams params = new ImportParams();
  80. params.setTitleRows(titleRows);
  81. params.setHeadRows(headerRows);
  82. params.setNeedSave(true);
  83. params.setSaveUrl("/excel/");
  84. try {
  85. return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
  86. } catch (NoSuchElementException e) {
  87. throw new IOException("模板不能为空");
  88. } catch (Exception e) {
  89. throw new IOException(e.getMessage());
  90. }
  91. }
  92. /** * excel 导入 * * @param file 上传的文件 * @param titleRows 表格内数据标题行 * @param headerRows 表头行 * @param pojoClass pojo类型 * @param <T> * @return */
  93. public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
  94. if (file == null) {
  95. return null;
  96. }
  97. try {
  98. return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass);
  99. } catch (Exception e) {
  100. throw new IOException(e.getMessage());
  101. }
  102. }
  103. /** * excel 导入 * * @param inputStream 文件输入流 * @param titleRows 表格内数据标题行 * @param headerRows 表头行 * @param pojoClass pojo类型 * @param <T> * @return */
  104. public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
  105. if (inputStream == null) {
  106. return null;
  107. }
  108. ImportParams params = new ImportParams();
  109. params.setTitleRows(titleRows);
  110. params.setHeadRows(headerRows);
  111. params.setSaveUrl("/excel/");
  112. params.setNeedSave(true);
  113. try {
  114. return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
  115. } catch (NoSuchElementException e) {
  116. throw new IOException("excel文件不能为空");
  117. } catch (Exception e) {
  118. throw new IOException(e.getMessage());
  119. }
  120. }
  121. }

4)创建数据库db2020及表user,执行脚本在根目录下。

5)excel表格要导入的数据文件在项目根路径的template文件夹下

6)使用vue-cli新建一个vue的项目,并安装需要的插件。项目对axios进行了封装,调用的时候,直接在js中使用即可,详见源码。

7)最后一点,要配置文件中加一行配置

  1. #easypoi启用覆盖
  2. spring
  3. main:
  4. allow-bean-definition-overriding: true

1.2导入

excel文件的导入,主要就是把文件上传之后把内容读取出来进行相应的操作。

1)编写controller导入接口,service及dao详见源码。

  1. /** * 导入数据 * @param file * @return * @throws IOException */
  2. @RequestMapping(value = "/import", method = RequestMethod.POST)
  3. public CommonResult importExcel(@RequestParam("file") MultipartFile file) throws IOException {
  4. List<User> list = ExcelUtils.importExcel(file, User.class);
  5. int i = userService.insertByBatch(list);
  6. if (i != 0) {
  7. return new CommonResult(200, "导入成功");
  8. } else {
  9. return new CommonResult(444, "导入失败");
  10. }
  11. }

2)新建User实体类,给属性添加@Excel注解

  1. package com.example.easypoidemoadmin.entity;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.Data;
  7. /** * @dec 用户实体 */
  8. @Data
  9. @TableName(value = "User")
  10. public class User {
  11. /** * 用户名 */
  12. @TableId(value = "username")
  13. @Excel(name = "用户名",)
  14. private String username;
  15. /** * 姓名 */
  16. @TableField(value = "name")
  17. @Excel(name = "姓名")
  18. private String name;
  19. /** * 年龄 */
  20. @TableField(value = "age")
  21. @Excel(name = "年龄")
  22. private Integer age;
  23. /** * 性别,0表示男,1表示女 */
  24. @TableField(value = "sex")
  25. @Excel(name = "性别",replace = {"男_0", "女_1"})
  26. private String sex;
  27. /** * 籍贯 */
  28. @TableField(value = "address")
  29. @Excel(name = "籍贯")
  30. private String address;
  31. }

需要注意的是,上述的导入的excel内容必须包含表头和标题,否则读取不到内容。在性别这里,分别使用数字代替文字,存储方便。

3)页面导入的组件

  1. <el-upload class="upload-demo" action="" :limit="1" :http-request="importExcel" :show-file-list="false" :file-list="fileList">
  2. <el-button size="small" type="primary" icon="el-icon-upload">导入</el-button>
  3. </el-upload>

4)页面导入的方法

  1. //导入
  2. importExcel(param) {
  3. const formData = new FormData()
  4. formData.append('file', param.file)
  5. home.upload(formData).then(res => {
  6. if (res.code == 200) {
  7. this.fileList = []
  8. this.$message.success("导入成功")
  9. this.getList()
  10. } else {
  11. this.$message.error("导入失败")
  12. }
  13. }).catch(err =>{
  14. console.log(err)
  15. this.$message.error("导入失败")
  16. })
  17. } 

导入的模板在后台代码的项目根目录下的template目录下。

5)注意事项

A:excel表格的表头必须和@Excel的name属性一样,否则读取不到数据。

B:若导入的字段包含日期类型,那么需要指定导入时的日期的格式并标明是必导入字段,如下所示,excel的内容的日期也需要是这种格式

  1. @Excel(name = "日期",isImportField = "true", importFormat = "yyyy-MM-dd" ,databaseFormat = "yyyy-MM-dd")

C:若导出的字段包含日期类型,那么需要指定导出的格式

  1. @Excel(name = "日期",exportFormat = "yyyy-MM-dd", databaseFormat = "yyyy-MM-dd")

二者综合的代码如下,下一小节的导出日期就不再说明。

  1. @Excel(name = "日期",isImportField = "true",exportFormat = "yyyy-MM-dd", importFormat = "yyyy-MM-dd" ,databaseFormat = "yyyy-MM-dd")

1.3导出

导入就是根据查询的条件把查询结果先写到excel表格中,然后下载这个excel即可。

1)编写controller导出接口,service及dao详见源码。

  1. /** * 导出数据,使用map接收 * * @param map * @param response * @throws IOException */
  2. @PostMapping("/exportExcel")
  3. public void exportExcel(@RequestBody Map<String, Object> map, HttpServletResponse response) throws IOException {
  4. IPage<User> iPage = userService.getList((String) map.get("name"), (Integer) map.get("page"), (Integer) map.get("limit"));
  5. ExcelUtils.exportExcel(iPage.getRecords(), (String) map.get("title"), (String) map.get("sheetName"), User.class, (String) map.get("fileName"), response);
  6. }

2)给实体类@Excel注解添加其他属性

  1. package com.example.easypoidemoadmin.entity;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.Data;
  7. /** * @dec 用户实体 */
  8. @Data
  9. @TableName(value = "User")
  10. public class User {
  11. /** * 用户名 */
  12. @TableId(value = "username")
  13. @Excel(name = "用户名", orderNum = "0", width = 30)
  14. private String username;
  15. /** * 姓名 */
  16. @TableField(value = "name")
  17. @Excel(name = "姓名", orderNum = "1", width = 30)
  18. private String name;
  19. /** * 年龄 */
  20. @TableField(value = "age")
  21. @Excel(name = "年龄", orderNum = "2", width = 30)
  22. private Integer age;
  23. /** * 性别,0表示男,1表示女 */
  24. @TableField(value = "sex")
  25. @Excel(name = "性别", orderNum = "3", width = 30,replace = {"男_0", "女_1"})
  26. private String sex;
  27. /** * 籍贯 */
  28. @TableField(value = "address")
  29. @Excel(name = "籍贯", orderNum = "4", width = 30)
  30. private String address;
  31. }

3)页面导出的方法

  1. //导出
  2. exportExcel() {
  3. this.downloadLoading = true
  4. home.exportExcel({
  5. title: '用户基本信息',
  6. sheetName: '用户信息',
  7. fileName: '用户信息表',
  8. name: this.pageData.name,
  9. page: this.pageData.page,
  10. limit: this.pageData.limit,
  11. }).then(res => {
  12. //使用js下载文件
  13. fileDownload(res, '用户信息表.xlsx')
  14. }).finally(() => {
  15. this.downloadLoading = false;
  16. });
  17. },

这里使用到了js-file-download插件,它是用来帮助下载文件的。当下载文件时,很多时候都是在地址栏输入url后浏览器自动帮忙下载,但是要统一请求方式,就把返回的二进制文件交给js-file-download进行处理后再下载。需要注意的是,这个导出的请求,我封装了一个单独的方法,需要指定响应的方式,否则无法下载后的文件是空的,方法截图如下:

1.4图片的导出

有了上面的导出基础,图片的导出就很简单了。

1)新建一个实体类,用于和上面的实体类区分

  1. package com.example.easypoidemoadmin.entity;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import lombok.Data;
  4. /** * @dec 描述 */
  5. @Data
  6. public class Company {
  7. @Excel(name = "公司名称",width =20)
  8. private String name;
  9. /** * type为 2 表示字段类型为图片 * imageType为 1 表示从file读取 */
  10. @Excel(name = "公司logo",width =20,type = 2,imageType = 1)
  11. private String logo;
  12. @Excel(name = "公司介绍",width =100)
  13. private String dec;
  14. public Company(String name,String logo,String dec){
  15. this.name=name;
  16. this.logo=logo;
  17. this.dec=dec;
  18. }
  19. }

2)创建接口,图片请自行下载。

  1. /** * 图片的导出 * * @param response * @throws IOException */
  2. @PostMapping("/imgexport")
  3. public void imgExport(HttpServletResponse response,@RequestBody Map<String, Object> map) throws IOException {
  4. List<Company> list = new ArrayList<>();
  5. //图片的路径自定义,但必须要正确
  6. list.add(new Company("百度", "E:/img/1.jpg", "百度一下你就知道"));
  7. list.add(new Company("腾讯", "E:/img/3.jpg", "腾讯qq,交流的世界"));
  8. list.add(new Company("阿里巴巴", "E:/img/2.jpg", "阿里巴巴,马云的骄傲"));
  9. String fileName = map.get("fileName").toString();
  10. ExcelUtils.exportExcel(list, fileName, fileName, Company.class, fileName, response);
  11. }

3)在页面添加导出的按钮,点击按钮即可进行下载,下载的文件如图

1.5图片的导入

1)给Company对象加上无参构造,否则会出现异常

  1. public Company(){}

2)导入接口

  1. /** * 导入图片 * @param file * @return * @throws IOException */
  2. @PostMapping("/imgimport")
  3. public CommonResult imgImport(@RequestParam("file") MultipartFile file) throws IOException {
  4. List<Company> list = ExcelUtils.importExcel(file, Company.class);
  5. return new CommonResult(200,"导入成功",list);
  6. }

3)参考excel的导入,添加一个导入的按钮和请求的方法,详见源码

4)点击excel图片上传,把上一步导出的文件进行导入,看到浏览器返回的数据如图

1.6excel模板导出文件

也可以使用固定的模板来导出excel。

1)在工具类添加方法

  1. /** * 根据模板生成excel后导出 * @param templatePath 模板路径 * @param map 数据集合 * @param fileName 文件名 * @param response * @throws IOException */
  2. public static void exportExcel(TemplateExportParams templatePath, Map<String, Object> map,String fileName, HttpServletResponse response) throws IOException {
  3. Workbook workbook = ExcelExportUtil.exportExcel(templatePath, map);
  4. downLoadExcel(fileName, response, workbook);
  5. }

2)编写模板excel。截图如下,模板文件在项目根路径的template文件夹下:

在两个大括号里写对应的数据名称。$fe用来遍历数据,fe的写法 fe标志 : list数据 单个元素数据(默认t,不需要写) {{$fe: maplist t.id }}

3)接口

  1. /** * 使用模板excel导出 * * @param response * @throws Exception */
  2. @PostMapping("/excelTemplate")
  3. public void makeExcelTemplate(HttpServletResponse response, @RequestBody Map<String, Object> param) throws Exception {
  4. TemplateExportParams templatePath = new TemplateExportParams("E:/excel/用户信息文件模板.xls");
  5. Map<String, Object> map = new HashMap<>();
  6. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  7. map.put("date", sdf.format(new Date()));
  8. map.put("user", "admin");
  9. IPage<User> ipages = userService.getList("", 1, 10);
  10. map.put("userList", ipages.getRecords());
  11. ExcelUtils.exportExcel(templatePath, map, param.get("fileName").toString(), response);
  12. }

在接口中,指定模板文件的路径,然后给定数据,map的key值要和模板的值保持一致。

4)页面添加按钮和请求方法,见源码。点击即可下载。

1.7excel转html

1)在工具类添加方法

  1. /** * excel转html预览 * @param filePath 文件路径 * @param response * @throws Exception */
  2. public static void excelToHtml(String filePath,HttpServletResponse response) throws Exception{
  3. ExcelToHtmlParams params = new ExcelToHtmlParams(WorkbookFactory.create(POICacheManager.getFile(filePath)),true);
  4. response.getOutputStream().write(ExcelXorHtmlUtil.excelToHtml(params).getBytes());
  5. }

2)编写接口

  1. /** * EXCEL转html预览 */
  2. @GetMapping("previewExcel")
  3. public void excelToHtml(HttpServletResponse response) throws Exception {
  4. ExcelUtils.excelToHtml("E:/excel/用户信息导入模板.xlsx",response);
  5. }

3)页面添加按钮和请求方法,见源码。点击即可在弹框中显示。

2.Word文件导出

2.1使用word模板导出

1)导入easypoi-base的依赖

  1. <dependency>
  2. <groupId>cn.afterturn</groupId>
  3. <artifactId>easypoi-base</artifactId>
  4. <version>${easypoi.version}</version>
  5. </dependency>

2)在工具类加两个方法

  1. /** * word下载 * * @param fileName 下载时的文件名称 * @param response * @param doc */
  2. private static void downLoadWord(String fileName, HttpServletResponse response, XWPFDocument doc) throws IOException {
  3. try {
  4. response.setCharacterEncoding("UTF-8");
  5. response.setHeader("content-Type", "application/msword");
  6. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".docx" , "UTF-8"));
  7. doc.write(response.getOutputStream());
  8. } catch (Exception e) {
  9. throw new IOException(e.getMessage());
  10. }
  11. }
  12. /** * word模板导出 * @param map * @param templatePath * @param fileName * @param response * @throws Exception */
  13. public static void WordTemplateExport(Map<String, Object> map,String templatePath,String fileName,HttpServletResponse response) throws Exception {
  14. XWPFDocument doc = WordExportUtil.exportWord07(templatePath, map);
  15. downLoadWord(fileName,response,doc);
  16. }

3)接口,模板文件在项目根路径的template文件夹下,图片自定义下载(注意:如果要设置图片,必须把导入的jar的版本改为3.3.0,否则会报错,原因是新版本没有这个实体类):

  1. /** * 使用模板word导出数据 * @param param * @param response */
  2. @PostMapping("/wordTemplate")
  3. public void makeWordTemplate(@RequestBody Map<String, Object> param,HttpServletResponse response) {
  4. Map<String, Object> map = new HashMap<>();
  5. map.put("name", "张三");
  6. map.put("nativePlace", "湖北武汉");
  7. map.put("age", "20");
  8. map.put("nation", "汉族");
  9. map.put("phone", "15685654524");
  10. map.put("experience", "湖北武汉,工作三年,java工程师");
  11. map.put("evaluate", "优秀,善良,老实");
  12. //设置图片,如果无图片,不设置即可
  13. WordImageEntity image = new WordImageEntity();
  14. image.setHeight(200);
  15. image.setWidth(150);
  16. image.setUrl("E:/excel/pic.jpg");
  17. image.setType(WordImageEntity.URL);
  18. map.put("picture", image);
  19. try {
  20. ExcelUtils.WordTemplateExport(map,"E:/excel/个人简历模板.docx",param.get("fileName").toString(),response);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. }

4)页面添加按钮和请求方法,见源码。点击即可下载。上面案例导出时有图片,如果不需要图片,可不设置图片路径即可。

2.2使用word模板导出多页

单模板生成多页数据在合适的场景也是需要的,比如一个订单详情信息模板,但是有很多订单,需要导入到一个word里面。

1)在工具类添加方法

  1. /** * word模板导出多页 * @param list * @param templatePath * @param fileName * @param response * @throws Exception */
  2. public static void WordTemplateExportMorePage(List<Map<String, Object>> list, String templatePath, String fileName, HttpServletResponse response) throws Exception {
  3. XWPFDocument doc = new ParseWord07().parseWord(templatePath, list);
  4. downLoadWord(fileName, response, doc);
  5. }

2)接口

  1. /** * word模板导出多页 * @param param * @param response */
  2. @PostMapping("/wordTemplateMorePage")
  3. public void makeWordTemplateMorePage(@RequestBody Map<String, Object> param, HttpServletResponse response) {
  4. List<Map<String, Object>> list=new ArrayList<>();
  5. for (int i = 0; i < 5; i++) {
  6. Map<String, Object> person = new HashMap<>();
  7. person.put("name", "张三"+i);
  8. person.put("nativePlace", "湖北武汉"+i);
  9. person.put("age", 20+i);
  10. person.put("nation", "汉族");
  11. person.put("phone", "15685654524");
  12. person.put("experience", "湖北武汉,工作三年,java工程师");
  13. person.put("evaluate", "优秀,善良,老实");
  14. person.put("picture", "");
  15. list.add(person);
  16. }
  17. try {
  18. ExcelUtils.WordTemplateExportMorePage(list, "E:/excel/个人简历模板.docx", param.get("fileName").toString(), response);
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. }

3)页面添加按钮和请求方法,见源码。点击即可下载。

3.excel导入时验证

有时候需要在导入时先验证数据的合法性再进行导出,为了演示的完整性,需要使用新的页面进行导入操作。步骤如下:

3.1环境准备

1)新建表student

  1. CREATE TABLE `student` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  4. `age` int(11) DEFAULT NULL COMMENT '年龄',
  5. `birth` date DEFAULT NULL COMMENT '出生日期',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

2)在ExcelUtils工具类添加方法(标红)

  1. package com.example.easypoidemoadmin.utils;
  2. import cn.afterturn.easypoi.cache.manager.POICacheManager;
  3. import cn.afterturn.easypoi.excel.ExcelExportUtil;
  4. import cn.afterturn.easypoi.excel.ExcelImportUtil;
  5. import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
  6. import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
  7. import cn.afterturn.easypoi.excel.entity.ExportParams;
  8. import cn.afterturn.easypoi.excel.entity.ImportParams;
  9. import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
  10. import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
  11. import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
  12. import cn.afterturn.easypoi.word.WordExportUtil;
  13. import cn.afterturn.easypoi.word.parse.ParseWord07;
  14. import org.apache.commons.lang3.StringUtils;
  15. import org.apache.poi.ss.usermodel.Workbook;
  16. import org.apache.poi.ss.usermodel.WorkbookFactory;
  17. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import javax.servlet.http.HttpServletResponse;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.net.URLEncoder;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.NoSuchElementException;
  28. /** * Excel导入导出工具类 */
  29. public class ExcelUtils {
  30. /** * excel 导出 * * @param list 数据列表 * @param fileName 导出时的excel名称 * @param response */
  31. public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
  32. defaultExport(list, fileName, response);
  33. }
  34. /** * 默认的 excel 导出 * * @param list 数据列表 * @param fileName 导出时的excel名称 * @param response */
  35. private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
  36. //把数据添加到excel表格中
  37. Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
  38. downLoadExcel(fileName, response, workbook);
  39. }
  40. /** * excel 导出 * * @param list 数据列表 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param response * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型) */
  41. private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
  42. //把数据添加到excel表格中
  43. Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
  44. downLoadExcel(fileName, response, workbook);
  45. }
  46. /** * excel 导出 * * @param list 数据列表 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型) * @param response */
  47. public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
  48. defaultExport(list, pojoClass, fileName, response, exportParams);
  49. }
  50. /** * excel 导出 * * @param list 数据列表 * @param title 表格内数据标题 * @param sheetName sheet名称 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param response */
  51. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
  52. defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
  53. }
  54. /** * 根据模板生成excel后导出 * * @param templatePath 模板路径 * @param map 数据集合 * @param fileName 文件名 * @param response * @throws IOException */
  55. public static void exportExcel(TemplateExportParams templatePath, Map<String, Object> map, String fileName, HttpServletResponse response) throws IOException {
  56. Workbook workbook = ExcelExportUtil.exportExcel(templatePath, map);
  57. downLoadExcel(fileName, response, workbook);
  58. }
  59. /** * excel 导出 * * @param list 数据列表 * @param title 表格内数据标题 * @param sheetName sheet名称 * @param pojoClass pojo类型 * @param fileName 导出时的excel名称 * @param isCreateHeader 是否创建表头 * @param response */
  60. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
  61. ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
  62. exportParams.setCreateHeadRows(isCreateHeader);
  63. defaultExport(list, pojoClass, fileName, response, exportParams);
  64. }
  65. /** * excel下载 * * @param fileName 下载时的文件名称 * @param response * @param workbook excel数据 */
  66. private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
  67. try {
  68. response.setCharacterEncoding("UTF-8");
  69. response.setHeader("content-Type", "application/vnd.ms-excel");
  70. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
  71. workbook.write(response.getOutputStream());
  72. } catch (Exception e) {
  73. throw new IOException(e.getMessage());
  74. }
  75. }
  76. /** * word下载 * * @param fileName 下载时的文件名称 * @param response * @param doc */
  77. private static void downLoadWord(String fileName, HttpServletResponse response, XWPFDocument doc) throws IOException {
  78. try {
  79. response.setCharacterEncoding("UTF-8");
  80. response.setHeader("content-Type", "application/msword");
  81. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".docx", "UTF-8"));
  82. doc.write(response.getOutputStream());
  83. } catch (Exception e) {
  84. throw new IOException(e.getMessage());
  85. }
  86. }
  87. /** * excel 导入 * * @param file excel文件 * @param pojoClass pojo类型 * @param <T> * @return */
  88. public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
  89. return importExcel(file, 1, 1, pojoClass);
  90. }
  91. /** * excel 导入 * * @param filePath excel文件路径 * @param titleRows 表格内数据标题行 * @param headerRows 表头行 * @param pojoClass pojo类型 * @param <T> * @return */
  92. public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
  93. if (StringUtils.isBlank(filePath)) {
  94. return null;
  95. }
  96. ImportParams params = new ImportParams();
  97. params.setTitleRows(titleRows);
  98. params.setHeadRows(headerRows);
  99. params.setNeedSave(true);
  100. params.setSaveUrl("/excel/");
  101. try {
  102. return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
  103. } catch (NoSuchElementException e) {
  104. throw new IOException("模板不能为空");
  105. } catch (Exception e) {
  106. throw new IOException(e.getMessage());
  107. }
  108. }
  109. /** * excel 导入 * * @param file 上传的文件 * @param titleRows 表格内数据标题行 * @param headerRows 表头行 * @param pojoClass pojo类型 * @param <T> * @return */
  110. public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
  111. if (file == null) {
  112. return null;
  113. }
  114. try {
  115. return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass);
  116. } catch (Exception e) {
  117. throw new IOException(e.getMessage());
  118. }
  119. }
  120. /** * excel 导入 * * @param inputStream 文件输入流 * @param titleRows 表格内数据标题行 * @param headerRows 表头行 * @param pojoClass pojo类型 * @param <T> * @return */
  121. public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
  122. if (inputStream == null) {
  123. return null;
  124. }
  125. ImportParams params = new ImportParams();
  126. params.setTitleRows(titleRows);
  127. params.setHeadRows(headerRows);
  128. params.setSaveUrl("/excel/");
  129. params.setNeedSave(true);
  130. try {
  131. return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
  132. } catch (NoSuchElementException e) {
  133. throw new IOException("excel文件不能为空");
  134. } catch (Exception e) {
  135. throw new IOException(e.getMessage());
  136. }
  137. }
  138. /** * excel转html预览 * * @param filePath 文件路径 * @param response * @throws Exception */
  139. public static void excelToHtml(String filePath, HttpServletResponse response) throws Exception {
  140. ExcelToHtmlParams params = new ExcelToHtmlParams(WorkbookFactory.create(POICacheManager.getFile(filePath)), true);
  141. response.getOutputStream().write(ExcelXorHtmlUtil.excelToHtml(params).getBytes());
  142. }
  143. /** * word模板导出 * * @param map * @param templatePath * @param fileName * @param response * @throws Exception */
  144. public static void WordTemplateExport(Map<String, Object> map, String templatePath, String fileName, HttpServletResponse response) throws Exception {
  145. XWPFDocument doc = WordExportUtil.exportWord07(templatePath, map);
  146. downLoadWord(fileName, response, doc);
  147. }
  148. /** * word模板导出多页 * * @param list * @param templatePath * @param fileName * @param response * @throws Exception */
  149. public static void WordTemplateExportMorePage(List<Map<String, Object>> list, String templatePath, String fileName, HttpServletResponse response) throws Exception {
  150. XWPFDocument doc = new ParseWord07().parseWord(templatePath, list);
  151. downLoadWord(fileName, response, doc);
  152. }
  153. /** * excel 导入,有错误信息 * * @param file 上传的文件 * @param pojoClass pojo类型 * @param <T> * @return */
  154. public static <T> ExcelImportResult<T> importExcelMore(MultipartFile file, Class<T> pojoClass) throws IOException {
  155. if (file == null) {
  156. return null;
  157. }
  158. try {
  159. return importExcelMore(file.getInputStream(), pojoClass);
  160. } catch (Exception e) {
  161. throw new IOException(e.getMessage());
  162. }
  163. }
  164. /** * excel 导入 * * @param inputStream 文件输入流 * @param pojoClass pojo类型 * @param <T> * @return */
  165. private static <T> ExcelImportResult<T> importExcelMore(InputStream inputStream, Class<T> pojoClass) throws IOException {
  166. if (inputStream == null) {
  167. return null;
  168. }
  169. ImportParams params = new ImportParams();
  170. params.setTitleRows(1);//表格内数据标题行
  171. params.setHeadRows(1);//表头行
  172. params.setSaveUrl("/excel/");
  173. params.setNeedSave(true);
  174. params.setNeedVerify(true);
  175. try {
  176. return ExcelImportUtil.importExcelMore(inputStream, pojoClass, params);
  177. } catch (NoSuchElementException e) {
  178. throw new IOException("excel文件不能为空");
  179. } catch (Exception e) {
  180. throw new IOException(e.getMessage());
  181. }
  182. }
  183. }

3)导入验证构造器的依赖

  1. <dependency>
  2. <groupId>org.hibernate</groupId>
  3. <artifactId>hibernate-validator</artifactId>
  4. <version>5.4.0.Final</version>
  5. </dependency>

4)创建easypoi的工具类

  1. package com.example.easypoidemoadmin.utils;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import org.apache.commons.lang3.StringUtils;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.InvocationHandler;
  6. import java.lang.reflect.Proxy;
  7. import java.util.Map;
  8. /** * easypoi工具类, * 使用new方式创建对象并使用 * * @param <T> */
  9. public class EasyPoiTool<T> {
  10. /** * 需要被反射的对象,使用泛型规范传入对象 */
  11. public T t;
  12. /** * 修改注解@Excel的属性值 * @param attributeName * @param columnName * @param targetValue * @throws Exception */
  13. public void changeAttribute(String attributeName, String columnName, Object targetValue) throws Exception {
  14. if (t == null) {
  15. throw new ClassNotFoundException("未找到目标类");
  16. }
  17. if (StringUtils.isEmpty(attributeName)) {
  18. throw new NullPointerException("传入的注解属性为空");
  19. }
  20. if (StringUtils.isEmpty(columnName)) {
  21. throw new NullPointerException("传入的属性列名为空");
  22. }
  23. //获取目标对象的属性值
  24. Field field = t.getClass().getDeclaredField(columnName);
  25. //获取注解反射对象
  26. Excel excelAnion = field.getAnnotation(Excel.class);
  27. //获取代理
  28. InvocationHandler invocationHandler = Proxy.getInvocationHandler(excelAnion);
  29. Field excelField = invocationHandler.getClass().getDeclaredField("memberValues");
  30. excelField.setAccessible(true);
  31. Map memberValues = (Map) excelField.get(invocationHandler);
  32. memberValues.put(attributeName, targetValue);
  33. }
  34. }

3.2实战演练

需求:对导入的学生信息进行验证,验证通过后才能导入。要求学生姓名不能为空,出生日期必须是yyyy-MM-dd格式,年龄必须合法。导入后把验证未通过的信息通过excel方式再下载到本地。

1)新建学生对象,添加注解验证并实现IExcelModel接口

  1. package com.example.easypoidemoadmin.entity;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import cn.afterturn.easypoi.handler.inter.IExcelModel;
  4. import com.baomidou.mybatisplus.annotation.IdType;
  5. import com.baomidou.mybatisplus.annotation.TableField;
  6. import com.baomidou.mybatisplus.annotation.TableId;
  7. import com.baomidou.mybatisplus.annotation.TableName;
  8. import com.fasterxml.jackson.annotation.JsonFormat;
  9. import lombok.Data;
  10. import javax.validation.constraints.NotNull;
  11. import javax.validation.constraints.Pattern;
  12. import java.util.Date;
  13. @Data
  14. @TableName(value = "student")
  15. public class Student implements IExcelModel {
  16. /** * id */
  17. @TableId(value = "id", type = IdType.AUTO)
  18. private Integer id;
  19. /** * 姓名 */
  20. @TableField(value = "name")
  21. @Excel(name = "姓名", width = 20)
  22. @NotNull(message = "姓名不能为空")
  23. private String name;
  24. /** * 年龄 */
  25. @TableField(value = "age")
  26. private Integer age;
  27. /** * 年龄验证 */
  28. @TableField(exist = false)
  29. @Excel(name = "年龄")
  30. @NotNull(message = "年龄不能为空")
  31. @Pattern(regexp = "^(?:[1-9][0-9]?|1[01][0-9]|120)$", message = "年龄必须是整数,且在1-120之间")
  32. private String ageStr;
  33. /** * 出生日期 */
  34. @TableField(value = "birth")
  35. @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
  36. private Date birth;
  37. /** * 出生日期验证 */
  38. @TableField(exist = false)
  39. @Excel(name = "出生日期", isImportField = "true", importFormat = "yyyy-MM-dd", databaseFormat = "yyyy-MM-dd", width = 30)
  40. @NotNull(message = "出生日期不能为空")
  41. @Pattern(regexp = "^\\d{4}-\\d{1,2}-\\d{1,2}$", message = "日期格式必须是yyyy-MM-dd格式,如2020-01-01")
  42. private String birthStr;
  43. //错误信息
  44. @TableField(exist = false)
  45. @Excel(name = "错误信息", width = 50, isColumnHidden = true)
  46. private String errorMsg;
  47. }

实现此接口的原因是获取其验证的错误信息,并将其映射到字段errorMsg上,当对象不包含此字段时,就看不到错误信息。

2)新建接口StudentController

  1. package com.example.easypoidemoadmin.controller;
  2. import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.example.easypoidemoadmin.entity.CommonResult;
  5. import com.example.easypoidemoadmin.entity.Student;
  6. import com.example.easypoidemoadmin.service.StudentService;
  7. import com.example.easypoidemoadmin.utils.EasyPoiTool;
  8. import com.example.easypoidemoadmin.utils.ExcelUtils;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.web.bind.annotation.*;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.IOException;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import java.util.Map;
  17. @RestController
  18. @RequestMapping("/api/student")
  19. public class StudentController {
  20. @Autowired
  21. private StudentService studentService;
  22. /** * 查询用户信息列表 * * @param name * @param page * @param limit * @return */
  23. @GetMapping("/list")
  24. public CommonResult getList(String name, Integer page, Integer limit) {
  25. IPage<Student> iPage = studentService.getList(name, page, limit);
  26. return new CommonResult(200, "查询信息成功", iPage.getRecords(), iPage.getTotal());
  27. }
  28. /** * 导入学生信息 * * @param file * @param response * @return */
  29. @PostMapping("/upload")
  30. public CommonResult upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
  31. try {
  32. ExcelImportResult<Student> importResult = ExcelUtils.importExcelMore(file, Student.class);
  33. //验证通过的数据
  34. List<Student> list = importResult.getList();
  35. //验证未通过的数据
  36. List<Student> failList = importResult.getFailList();
  37. studentService.insertBatch(list);
  38. if (failList != null && failList.size() > 0) {
  39. //修改导出的日期格式
  40. EasyPoiTool<Student> easyPoiUtil = new EasyPoiTool<>();
  41. easyPoiUtil.t = failList.get(0);
  42. //展示错误的列
  43. easyPoiUtil.changeAttribute("isColumnHidden", "errorMsg", false);
  44. //设置导出的格式
  45. easyPoiUtil.changeAttribute("exportFormat", "birthStr", "");
  46. //导出excel
  47. String title = "导入异常的数据";
  48. ExcelUtils.exportExcel(failList, title, title, Student.class, title, response);
  49. return null;
  50. }
  51. return new CommonResult(200, "信息导入成功");
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. return new CommonResult(444, "信息导入失败");
  55. }
  56. }
  57. @PostMapping("/exportTemplate")
  58. public void exportTemplate(@RequestBody Map<String, Object> map, HttpServletResponse response) throws IOException {
  59. List<Student> list = new ArrayList<>();
  60. ExcelUtils.exportExcel(list, (String) map.get("title"), (String) map.get("sheetName"), Student.class, (String) map.get("fileName"), response);
  61. }
  62. }

对于后面的service和dao详见源码。

3)导入的页面见源码,这里主要说明导入的方法,在导入后需要根据返回的数据判断是否有错误的信息,如果有则下载错误信息,若没有则显示成功。

  1. importExcel(param) {
  2. const file = param.file
  3. if (file.name.lastIndexOf('.') < 0) {
  4. this.$message.error('上传文件只能是xls、xlsx格式!')
  5. return
  6. }
  7. const testMsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
  8. const extensionXLS = testMsg == 'xls'
  9. const extensionXLSX = testMsg == 'xlsx'
  10. if (!extensionXLS && !extensionXLSX) {
  11. this.$message.error('上传文件只能是xls、xlsx格式!')
  12. return
  13. }
  14. const isLt2M = file.size / 1024 / 1024 < 2
  15. if (!isLt2M) {
  16. this.$message.error('上传文件不能超过 2MB!')
  17. return
  18. }
  19. this.importLoading = true
  20. const formData = new FormData()
  21. formData.append('file', param.file)
  22. student.upload(formData).then(res => {
  23. if (!res.code) {
  24. this.$message.error("部分数据导入失败,数据已下载到本地,请查看!")
  25. fileDownload(res, '导入异常的数据.xlsx')
  26. this.fileList = []
  27. this.getList()
  28. } else if (res.code == 200) {
  29. this.$message.success("导入成功")
  30. this.fileList = []
  31. this.getList()
  32. } else {
  33. this.$message.error("导入失败")
  34. }
  35. }).catch(err => {
  36. console.log(err)
  37. this.$message.error("导入失败")
  38. }).finally(()=>{
  39. this.importLoading = false
  40. })
  41. },

也就是说对于这个上传的请求,当返回的内容是json字符串时就是成功的,没有错误的数据,若不是则返回的是arraybuff类型的数据,需要直接下载。

3.3注意事项

1)由于需要进行验证,因此在工具类中必须要设置ImportParams的needVerify为true;

2)easypoi是使用springboot对应的版本,对于spring的版本,验证在这里可能不生效;

3)对于验证构造器hibernate的版本,springboot2对应的版本必须是5及以上,否则错误信息不会显示;

4)对应上传的方法,响应类型必须是arraybuff,否则下载的excel无法打开

5)要显示错误的信息,必须设置errorMsg上@Excel注解的isColumnHidden为false

6)在@Excel中没有设置导出(exportFormat)的日期格式,而是在需要导出的时候再通过反射的方式(调用EasyPoiUtil的方法)设置。若提前设置了,在导入时,输入的格式不正确,在导出错误信息时则会抛出异常。

7)其自带的正则验证,要求字段的类型必须是字符串类型,其他类型会发生异常。因此,需要设置两个字段,一个映射数据库的字段,一个用于导出和导出。当然也可以使用两个类进行分布对应。

8)当需要获取错误的行号时,让实体类继承IExcelDataModel类并添加int类型的rowNum属性即可。

就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !

相关文章