当前位置:   article > 正文

Springboot与easypoi

Springboot与easypoi

一、介绍

        Easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板语言(熟悉的表达式语法),完成以前复杂的写法。在项目中添加依赖即可:

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

二、相关注解

        注解有5类分别是:

  • @Excel 作用到filed上面,是对Excel一列的一个描述
  • @ExcelCollection 表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示
  • @ExcelEntity 表示一个继续深入导出的实体,但他没有太多的实际意义,只是告诉系统这个对象里面同样有导出的字段
  • @ExcelIgnore 和名字一样表示这个字段被忽略跳过这个导导出
  • @ExcelTarget 这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理

1、@Excel

        这个是必须使用的注解,如果需求简单只使用这一个注解也是可以的,涵盖了常用的Excel需求。

属性类型默认值功能
nameStringnull列名
needMergebooleanfasle是否需要纵向合并单元格(用于含有list中,单个的单元格,合并list创建的多个row)
orderNumString"0"列的排序
replaceString[]{}值得替换,导出是{a_id,b_id} 导入反过来
savePathString"upload"导入文件保存路径,如果是图片可以填写,默认是upload/className/ IconEntity这个类对应的就是upload/Icon/
typeint1导出类型 1 是文本 2 是图片,3 是函数,10 是数字 默认是文本
widthdouble10列宽
heightdouble10列高,后期打算统一使用@ExcelTarget的height,这个会被废弃
isStatisticsbooleanfasle自动统计数据,在追加一行统计,把所有数据都和输出。这个处理会吞没异常,请注意这一点
isHyperlinkbooleanfalse超链接,如果是需要实现接口返回对象
isImportFieldbooleantrue校验字段,看看这个字段是不是导入的Excel中有,如果没有说明是错误的Excel,读取失败
exportFormatString""导出的时间格式,以这个是否为空来判断是否需要格式化日期
importFormatString""导入的时间格式,以这个是否为空来判断是否需要格式化日期
formatString""时间格式,相当于同时设置了exportFormat 和 importFormat
databaseFormatString"yyyyMMddHHmmss"导出时间设置,如果字段是Date类型则不需要设置 数据库如果是string 类型,这个需要设置这个数据库格式,用以转换时间格式输出
numFormatString""数字格式化,参数是Pattern,使用的对象是DecimalFormat
imageTypeint1导出类型 1 从file读取 2 是从数据库中读取 默认是文件 同样导入也是一样的
suffixString""文字后缀,如% 90 变成90%
isWrapbooleantrue是否换行 即支持\n
mergeRelyint[]{}合并单元格依赖关系,比如第二列合并是基于第一列 则{0}就可以了
mergeVerticalbooleanfasle纵向合并内容相同的单元格
fixedIndexint-1对应excel的列,忽略名字
isColumnHiddenbooleanfalse导出隐藏列

2、@ExcelTarget

        限定一个导出实体的注解,以及一些通用设置,作用于最外面的实体。

属性类型默认值功能

value

String

null

定义ID

height

double

10

设置行高

fontSize

short

11

设置文字大小

3、@ExcelEntity

        标记是不是导出excel 标记为实体类,标记是否继续穿透,可以自定义内部id。

属性类型默认值功能

id

String

null

定义ID

4、@ExcelCollection

        一对多的集合注解,用以标记集合是否被数据以及集合的整体排序

属性类型默认值功能

id

String

null

定义ID

name

String

null

定义集合列名

orderNum

int

0

排序

type

Class<?>

ArrayList.class

导入时创建对象使用

5、@ExcelIgnore

        忽略这个属性,多使用需循环引用中。

三、easypoi提供的类

1、ExportParams

        导出参数,主要来定义 Excel的一些信息,在ExcelExportUtil 里面进行文件导出的,都是使用这个参数来作为导出参数。

  1. /**
  2. * Excel 导出参数
  3. */
  4. @Data
  5. public class ExportParams extends ExcelBaseParams {
  6. /**
  7. * 表格第一行title名称
  8. */
  9. private String title;
  10. /**
  11. * 表格第一行title高度
  12. */
  13. private short titleHeight = 10;
  14. /**
  15. * 表格第一行子title名称
  16. */
  17. private String secondTitle;
  18. /**
  19. * 表格第一行子title高度
  20. */
  21. private short secondTitleHeight = 8;
  22. /**
  23. * sheetName
  24. */
  25. private String sheetName;
  26. /**
  27. * 过滤的属性
  28. */
  29. private String[] exclusions;
  30. /**
  31. * 是否添加index
  32. */
  33. private boolean addIndex;
  34. /**
  35. * index名称
  36. */
  37. private String indexName = "序号";
  38. /**
  39. * 冰冻列
  40. */
  41. private int freezeCol;
  42. /**
  43. * 表头颜色 & 标题颜色
  44. */
  45. private short color = HSSFColor.HSSFColorPredefined.WHITE.getIndex();
  46. /**
  47. * 第二行标题颜色
  48. * 属性说明行的颜色 例如:HSSFColor.SKY_BLUE.index 默认
  49. */
  50. private short headerColor = HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex();
  51. /**
  52. * Excel 导出版本
  53. */
  54. private ExcelType type = ExcelType.HSSF;
  55. /**
  56. * Excel 导出style
  57. */
  58. private Class<?> style = ExcelExportStylerDefaultImpl.class;
  59. /**
  60. * 表头高度
  61. */
  62. private double headerHeight = 9D;
  63. /**
  64. * 是否创建表头
  65. */
  66. private boolean isCreateHeadRows = true;
  67. /**
  68. * 是否动态获取数据
  69. */
  70. private boolean isDynamicData = false;
  71. /**
  72. * 是否追加图形
  73. */
  74. private boolean isAppendGraph = true;
  75. /**
  76. * 是否固定表头
  77. */
  78. private boolean isFixedTitle = true;
  79. /**
  80. * 单sheet最大值
  81. * 03版本默认6W行,07默认100W
  82. */
  83. private int maxNum = 0;
  84. /**
  85. * 导出时在excel中每个列的高度 单位为字符,一个汉字=2个字符
  86. * 全局设置,优先使用
  87. */
  88. private short height = 0;
  89. /**
  90. * 只读
  91. */
  92. private boolean readonly = false;
  93. /**
  94. * 列宽自适应,如果没有设置width 也自适应宽度
  95. */
  96. private boolean autoSize = false;
  97. public ExportParams() {
  98. }
  99. public ExportParams(String title, String sheetName) {
  100. this.title = title;
  101. this.sheetName = sheetName;
  102. }
  103. public ExportParams(String title, String sheetName, ExcelType type) {
  104. this.title = title;
  105. this.sheetName = sheetName;
  106. this.type = type;
  107. }
  108. public ExportParams(String title, String secondTitle, String sheetName) {
  109. this.title = title;
  110. this.secondTitle = secondTitle;
  111. this.sheetName = sheetName;
  112. }
  113. public short getSecondTitleHeight() {
  114. return (short) (secondTitleHeight * 50);
  115. }
  116. public short getTitleHeight() {
  117. return (short) (titleHeight * 50);
  118. }
  119. public short getHeight() {
  120. return height == -1 ? -1 : (short) (height * 50);
  121. }
  122. public short getHeaderHeight() {
  123. return (short) (titleHeight * 50);
  124. }
  125. }

2、ExcelExportUtil

        导出工具类。构造导出需要的参数ExportParams,用该类中的静态方法进行导出指定excel文件。源码中对应的方法与参数含义如下:

  1. /**
  2. * excel 导出工具类
  3. */
  4. public final class ExcelExportUtil {
  5. public static int USE_SXSSF_LIMIT = 1000000;
  6. public static final String SHEET_NAME = "sheetName";
  7. private ExcelExportUtil() {
  8. }
  9. /**
  10. * 大数据量导出
  11. *
  12. * @param entity 表格标题属性
  13. * @param pojoClass Excel对象Class
  14. */
  15. public static IWriter<Workbook> exportBigExcel(ExportParams entity, Class<?> pojoClass) {
  16. ExcelBatchExportService batchServer = new ExcelBatchExportService();
  17. batchServer.init(entity, pojoClass);
  18. return batchServer;
  19. }
  20. /**
  21. * 大数据量导出
  22. *
  23. * @param entity 表格标题属性
  24. * @param excelParams cell映射类参数list
  25. * @return
  26. */
  27. public static IWriter<Workbook> exportBigExcel(ExportParams entity, List<ExcelExportEntity> excelParams) {
  28. ExcelBatchExportService batchServer = new ExcelBatchExportService();
  29. batchServer.init(entity, excelParams);
  30. return batchServer;
  31. }
  32. /**
  33. * 大数据量导出
  34. *
  35. * @param entity 表格标题属性
  36. * @param pojoClass Excel对象Class
  37. * @param server 查询数据的接口
  38. * @param queryParams 查询数据的参数
  39. */
  40. public static Workbook exportBigExcel(ExportParams entity, Class<?> pojoClass,
  41. IExcelExportServer server, Object queryParams) {
  42. ExcelBatchExportService batchServer = new ExcelBatchExportService();
  43. batchServer.init(entity, pojoClass);
  44. return batchServer.exportBigExcel(server, queryParams);
  45. }
  46. /**
  47. * 大数据量导出
  48. * @param entity 表格标题属性
  49. * @param excelParams 表格标题属性
  50. * @param server 查询数据的接口
  51. * @param queryParams 查询数据的参数
  52. * @return
  53. */
  54. public static Workbook exportBigExcel(ExportParams entity, List<ExcelExportEntity> excelParams,
  55. IExcelExportServer server, Object queryParams) {
  56. ExcelBatchExportService batchServer = new ExcelBatchExportService();
  57. batchServer.init(entity, excelParams);
  58. return batchServer.exportBigExcel(server, queryParams);
  59. }
  60. /**
  61. * @param entity 表格标题属性
  62. * @param pojoClass Excel对象Class
  63. * @param dataSet Excel对象数据List
  64. */
  65. public static Workbook exportExcel(ExportParams entity, Class<?> pojoClass,
  66. Collection<?> dataSet) {
  67. Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
  68. new ExcelExportService().createSheet(workbook, entity, pojoClass, dataSet);
  69. return workbook;
  70. }
  71. private static Workbook getWorkbook(ExcelType type, int size) {
  72. if (ExcelType.HSSF.equals(type)) {
  73. return new HSSFWorkbook();
  74. } else {
  75. return new XSSFWorkbook();
  76. }
  77. }
  78. /**
  79. * 根据Map创建对应的Excel
  80. *
  81. * @param entity 表格标题属性
  82. * @param entityList Map对象列表
  83. * @param dataSet Excel对象数据List
  84. */
  85. public static Workbook exportExcel(ExportParams entity, List<ExcelExportEntity> entityList,
  86. Collection<?> dataSet) {
  87. Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
  88. ;
  89. new ExcelExportService().createSheetForMap(workbook, entity, entityList, dataSet);
  90. return workbook;
  91. }
  92. /**
  93. * 根据Map创建对应的Excel(一个excel 创建多个sheet)
  94. *
  95. * @param list 多个Map key title 对应表格Title key entity 对应表格对应实体 key data
  96. * Collection 数据
  97. */
  98. public static Workbook exportExcel(List<Map<String, Object>> list, ExcelType type) {
  99. Workbook workbook = getWorkbook(type, 0);
  100. for (Map<String, Object> map : list) {
  101. ExcelExportService service = new ExcelExportService();
  102. ExportParams params = (ExportParams) map.get("title");
  103. params.setType(type);
  104. service.createSheet(workbook,params,
  105. (Class<?>) map.get("entity"), (Collection<?>) map.get("data"));
  106. }
  107. return workbook;
  108. }
  109. /**
  110. * 导出文件通过模板解析,不推荐这个了,推荐全部通过模板来执行处理
  111. * @param params 导出参数类
  112. * @param pojoClass 对应实体
  113. * @param dataSet 实体集合
  114. * @param map 模板集合
  115. * @return
  116. */
  117. @Deprecated
  118. public static Workbook exportExcel(TemplateExportParams params, Class<?> pojoClass,
  119. Collection<?> dataSet, Map<String, Object> map) {
  120. return new ExcelExportOfTemplateUtil().createExcelByTemplate(params, pojoClass, dataSet,
  121. map);
  122. }
  123. /**
  124. * 导出文件通过模板解析只有模板,没有集合
  125. *
  126. * @param params 导出参数类
  127. * @param map 模板集合
  128. * @return
  129. */
  130. public static Workbook exportExcel(TemplateExportParams params, Map<String, Object> map) {
  131. return new ExcelExportOfTemplateUtil().createExcelByTemplate(params, null, null, map);
  132. }
  133. /**
  134. * 导出文件通过模板解析只有模板,没有集合
  135. * 每个sheet对应一个map,导出到处,key是sheet的NUM
  136. *
  137. * @param params 导出参数类
  138. * @param map 模板集合
  139. * @return
  140. */
  141. public static Workbook exportExcel(Map<Integer, Map<String, Object>> map,
  142. TemplateExportParams params) {
  143. return new ExcelExportOfTemplateUtil().createExcelByTemplate(params, map);
  144. }
  145. /**
  146. * 导出文件通过模板解析只有模板,没有集合
  147. * 每个sheet对应一个list,按照数量进行导出排序,key是sheet的NUM
  148. *
  149. * @param params 导出参数类
  150. * @param map 模板集合
  151. * @return
  152. */
  153. public static Workbook exportExcelClone(Map<Integer, List<Map<String, Object>>> map,
  154. TemplateExportParams params) {
  155. return new ExcelExportOfTemplateUtil().createExcelCloneByTemplate(params, map);
  156. }
  157. }

3、ImportParams

        导入的参数设置,主要根据你文件里面的内容的格式来进行设置。

  1. /**
  2. * 导入参数设置
  3. */
  4. @Data
  5. public class ImportParams extends ExcelBaseParams {
  6. public static final String SAVE_URL = "/excel/upload/excelUpload";
  7. /**
  8. * 表格标题行数,默认0
  9. */
  10. private int titleRows = 0;
  11. /**
  12. * 表头行数,默认1
  13. */
  14. private int headRows = 1;
  15. /**
  16. * 字段真正值和列标题之间的距离 默认0
  17. */
  18. private int startRows = 0;
  19. /**
  20. * 主键设置,如何这个cell没有值,就跳过 或者认为这个是list的下面的值
  21. * 大家不理解,去掉这个
  22. */
  23. private Integer keyIndex = null;
  24. /**
  25. * 开始读取的sheet位置,默认为0
  26. */
  27. private int startSheetIndex = 0;
  28. /**
  29. * 上传表格需要读取的sheet 数量,默认为1
  30. */
  31. private int sheetNum = 1;
  32. /**
  33. * 是否需要保存上传的Excel,默认为false
  34. */
  35. private boolean needSave = false;
  36. /**
  37. * 校验组
  38. */
  39. private Class[] verifyGroup = null;
  40. /**
  41. * 是否需要校验上传的Excel,默认为false
  42. */
  43. private boolean needVerify = false;
  44. /**
  45. * 返回文件是否分割,默认是分割
  46. */
  47. private boolean verifyFileSplit = true;
  48. /**
  49. * 校验处理接口
  50. */
  51. private IExcelVerifyHandler verifyHandler;
  52. /**
  53. * 保存上传的Excel目录,默认是 如 TestEntity这个类保存路径就是
  54. * upload/excelUpload/Test/yyyyMMddHHmss_***** 保存名称上传时间_五位随机数
  55. */
  56. private String saveUrl = SAVE_URL;
  57. /**
  58. * 最后的无效行数
  59. */
  60. private int lastOfInvalidRow = 0;
  61. /**
  62. * 手动控制读取的行数
  63. */
  64. private int readRows = 0;
  65. /**
  66. * 导入时校验数据模板,是不是正确的Excel
  67. */
  68. private String[] importFields;
  69. /**
  70. * 导入时校验excel的标题列顺序。依赖于importFields的配置顺序
  71. */
  72. private boolean needCheckOrder = false;
  73. /**
  74. * Key-Value 读取标记,以这个为Key,后面一个Cell 为Value,多个改为ArrayList
  75. */
  76. private String keyMark = ":";
  77. /**
  78. * 按照Key-Value 规则读取全局扫描Excel,但是跳过List读取范围提升性能
  79. * 仅仅支持titleRows + headRows + startRows 以及 lastOfInvalidRow
  80. */
  81. private boolean readSingleCell = false;
  82. /**
  83. * 是否并行计算
  84. */
  85. private boolean concurrentTask = false;
  86. /**
  87. * 最小截取大小
  88. */
  89. private Integer critical = 1000;
  90. }

4、ExcelImportUtil

        导入工具。传入的文件、导出的entity的类,对应的import的参数来进行文件的导入。

  1. /**
  2. * Excel 导入工具
  3. */
  4. @SuppressWarnings({ "unchecked" })
  5. public class ExcelImportUtil {
  6. private ExcelImportUtil() {
  7. }
  8. private static final Logger LOGGER = LoggerFactory.getLogger(ExcelImportUtil.class);
  9. /**
  10. * Excel 导入 数据源本地文件,不返回校验结果 导入 字 段类型 Integer,Long,Double,Date,String,Boolean
  11. *
  12. * @param file 导入的文件
  13. * @param pojoClass 需要导入数据成的entity类
  14. * @param params 导入的参数
  15. * @return
  16. */
  17. public static <T> List<T> importExcel(File file, Class<?> pojoClass, ImportParams params) {
  18. FileInputStream in = null;
  19. try {
  20. in = new FileInputStream(file);
  21. return new ExcelImportService().importExcelByIs(in, pojoClass, params, false).getList();
  22. } catch (ExcelImportException e) {
  23. throw new ExcelImportException(e.getType(), e);
  24. } catch (Exception e) {
  25. LOGGER.error(e.getMessage(), e);
  26. throw new ExcelImportException(e.getMessage(), e);
  27. } finally {
  28. IOUtils.closeQuietly(in);
  29. }
  30. }
  31. /**
  32. * Excel 导入 数据源IO流,不返回校验结果 导入 字段类型 Integer,Long,Double,Date,String,Boolean
  33. *
  34. * @param inputstream 文件流
  35. * @param pojoClass 需要导入数据成的entity类
  36. * @param params 导入的参数
  37. */
  38. public static <T> List<T> importExcel(InputStream inputstream, Class<?> pojoClass,
  39. ImportParams params) throws Exception {
  40. return new ExcelImportService().importExcelByIs(inputstream, pojoClass, params, false).getList();
  41. }
  42. /**
  43. * Excel 导入 数据源IO流 字段类型 Integer,Long,Double,Date,String,Boolean
  44. * 支持校验,支持Key-Value
  45. *
  46. * @param inputstream 文件流
  47. * @param pojoClass 需要导入数据成的entity类
  48. * @param params 导入的参数
  49. */
  50. public static <T> ExcelImportResult<T> importExcelMore(InputStream inputstream,
  51. Class<?> pojoClass,
  52. ImportParams params) throws Exception {
  53. return new ExcelImportService().importExcelByIs(inputstream, pojoClass, params, true);
  54. }
  55. /**
  56. * Excel 导入 数据源本地文件 字段类型 Integer,Long,Double,Date,String,Boolean
  57. * 支持校验,支持Key-Value
  58. * @param inputstream 文件流
  59. * @param pojoClass 需要导入数据成的entity类
  60. * @param params 导入的参数
  61. */
  62. public static <T> ExcelImportResult<T> importExcelMore(File file, Class<?> pojoClass,
  63. ImportParams params) {
  64. FileInputStream in = null;
  65. try {
  66. in = new FileInputStream(file);
  67. return new ExcelImportService().importExcelByIs(in, pojoClass, params, true);
  68. } catch (ExcelImportException e) {
  69. throw new ExcelImportException(e.getType(), e);
  70. } catch (Exception e) {
  71. LOGGER.error(e.getMessage(), e);
  72. throw new ExcelImportException(e.getMessage(), e);
  73. } finally {
  74. IOUtils.closeQuietly(in);
  75. }
  76. }
  77. /**
  78. * Excel 通过SAX解析方法,适合大数据导入,不支持图片
  79. * 导入 数据源本地文件,不返回校验结果 导入字段类型 Integer,Long,Double,Date,String,Boolean
  80. *
  81. * @param inputstream 文件流
  82. * @param pojoClass 需要导入数据成的entity类
  83. * @param params 导入的参数
  84. * @param handler 接口自定义处理类,用来解析对象
  85. */
  86. public static void importExcelBySax(InputStream inputstream, Class<?> pojoClass,
  87. ImportParams params, IReadHandler handler) {
  88. new SaxReadExcel().readExcel(inputstream, pojoClass, params, handler);
  89. }
  90. }

四、使用案例

自定义easypoi工具类

  1. package com.ywz.utils;
  2. import cn.afterturn.easypoi.excel.ExcelExportUtil;
  3. import cn.afterturn.easypoi.excel.ExcelImportUtil;
  4. import cn.afterturn.easypoi.excel.entity.ExportParams;
  5. import cn.afterturn.easypoi.excel.entity.ImportParams;
  6. import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.poi.ss.usermodel.Workbook;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.File;
  12. import java.io.IOException;
  13. import java.net.URLEncoder;
  14. import java.util.List;
  15. import java.util.Map;
  16. import java.util.NoSuchElementException;
  17. /**
  18. * 类描述 -> EasyPoi工具类
  19. *
  20. * @Author: ywz
  21. * @Date: 2024/08/20
  22. */
  23. public class EasyPoiUtil {
  24. /**
  25. * 方法描述 -> 复杂导出Excel,包括文件名以及表名。创建表头
  26. *
  27. * @param list 导出的实体类
  28. * @param title 表头名称
  29. * @param sheetName sheet表名
  30. * @param pojoClass 映射的实体类
  31. * @param fileName 导出的文件名
  32. * @param isCreateHeader 是否创建表头
  33. * @Author: ywz
  34. * @Date: 2024/08/20
  35. */
  36. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
  37. ExportParams exportParams = new ExportParams(title, sheetName);
  38. exportParams.setCreateHeadRows(isCreateHeader);
  39. defaultExport(list, pojoClass, fileName, response, exportParams);
  40. }
  41. /**
  42. * 方法描述 -> 复杂导出Excel,包括文件名以及表名,不创建表头
  43. *
  44. * @param list 导出的实体类
  45. * @param title 表头名称
  46. * @param sheetName sheet表名
  47. * @param pojoClass 映射的实体类
  48. * @param fileName 导出的文件名
  49. * @Author: ywz
  50. * @Date: 2024/08/20
  51. */
  52. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
  53. defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
  54. }
  55. /**
  56. * 方法描述 -> Map 集合导出
  57. *
  58. * @param list 实体集合
  59. * @param fileName 导出的文件名称
  60. * @Author: ywz
  61. * @Date: 2024/08/20
  62. */
  63. public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
  64. defaultExport(list, fileName, response);
  65. }
  66. /**
  67. * 方法描述 -> 默认导出方法
  68. *
  69. * @param list 导出的实体集合
  70. * @param pojoClass pojo实体
  71. * @param fileName 导出的文件名
  72. * @param exportParams ExportParams封装实体
  73. * @Author: ywz
  74. * @Date: 2024/08/20
  75. */
  76. private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
  77. Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
  78. if (workbook != null) {
  79. downLoadExcel(fileName, response, workbook);
  80. }
  81. }
  82. /**
  83. * 方法描述 -> Excel导出
  84. *
  85. * @param fileName 文件名称
  86. * @param workbook Excel对象
  87. * @Author: ywz
  88. * @Date: 2024/08/20
  89. */
  90. private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
  91. try {
  92. response.setCharacterEncoding("UTF-8");
  93. response.setHeader("content-Type", "application/vnd.ms-excel");
  94. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  95. workbook.write(response.getOutputStream());
  96. } catch (IOException e) {
  97. throw new RuntimeException(e);
  98. }
  99. }
  100. /**
  101. * 方法描述 -> 默认导出方法
  102. *
  103. * @param list 导出的实体集合
  104. * @param fileName 导出的文件名
  105. * @Author: ywz
  106. * @Date: 2024/08/20
  107. */
  108. private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
  109. Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
  110. if (workbook != null) ;
  111. downLoadExcel(fileName, response, workbook);
  112. }
  113. /**
  114. * 方法描述 -> 根据文件路径来导入Excel
  115. *
  116. * @param filePath 文件路径
  117. * @param titleRows 表标题的行数
  118. * @param headerRows 表头行数
  119. * @param pojoClass Excel实体类
  120. * @Author: ywz
  121. * @Date: 2024/08/20
  122. */
  123. public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
  124. //判断文件是否存在
  125. if (StringUtils.isBlank(filePath)) {
  126. return null;
  127. }
  128. ImportParams params = new ImportParams();
  129. params.setTitleRows(titleRows);
  130. params.setHeadRows(headerRows);
  131. List<T> list = null;
  132. try {
  133. list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
  134. } catch (NoSuchElementException e) {
  135. throw new RuntimeException("模板不能为空");
  136. } catch (Exception e) {
  137. e.printStackTrace();
  138. }
  139. return list;
  140. }
  141. /**
  142. * 方法描述 -> 根据接收的Excel文件来导入Excel,并封装成实体类
  143. *
  144. * @param file 上传的文件
  145. * @param titleRows 表标题的行数
  146. * @param headerRows 表头行数
  147. * @param pojoClass Excel实体类
  148. * @Author: ywz
  149. * @Date: 2024/08/20
  150. */
  151. public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
  152. if (file == null) {
  153. return null;
  154. }
  155. ImportParams params = new ImportParams();
  156. params.setTitleRows(titleRows);
  157. params.setHeadRows(headerRows);
  158. List<T> list = null;
  159. try {
  160. list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
  161. } catch (NoSuchElementException e) {
  162. throw new RuntimeException("excel文件不能为空");
  163. } catch (Exception e) {
  164. throw new RuntimeException(e.getMessage());
  165. }
  166. return list;
  167. }
  168. }

定义实体类

  1. package com.ywz.entity;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.Data;
  6. import java.time.LocalDateTime;
  7. @ApiModel("用户实体类")
  8. @Data
  9. public class User {
  10. @ApiModelProperty("用户id")
  11. @Excel(name = "用户id", orderNum = "0")
  12. private Integer id;
  13. @ApiModelProperty("用户名")
  14. @Excel(name = "用户名", orderNum = "1")
  15. private String name;
  16. @ApiModelProperty("密码")
  17. @Excel(name = "密码", orderNum = "2")
  18. private String password;
  19. @ApiModelProperty("年龄")
  20. @Excel(name = "年龄", orderNum = "3")
  21. private Integer age;
  22. @ApiModelProperty("状态")
  23. @Excel(name = "状态", orderNum = "6", replace = {"正常_1", "禁用_0"})
  24. private Integer status;
  25. @ApiModelProperty("创建时间")
  26. @Excel(name = "创建时间", orderNum = "4", exportFormat = "yyyy-MM-dd HH:mm:ss")
  27. private LocalDateTime createTime;
  28. }

测试

        准备个excel文件进行导入:

        测试方法: 

  1. package com.ywz;
  2. import com.ywz.entity.User;
  3. import com.ywz.utils.EasyPoiUtil;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import java.util.List;
  7. @SpringBootTest
  8. public class EasyPoiTest {
  9. @Test
  10. public void importExcel() {
  11. String file = "D:\\用户表.xlsx";
  12. List<User> users = EasyPoiUtil.importExcel(file, 0, 1, User.class);
  13. System.out.println(users);
  14. }
  15. }

        在控制台查看导入成功:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/1017086
推荐阅读
相关标签
  

闽ICP备14008679号