当前位置:   article > 正文

EasyExcel实现导入导出Excel_easyexcel依赖哪些包

easyexcel依赖哪些包

平时项目经常用到导入导出功能,网上翻阅很多资料都没有找到理想的,这里做个记录

一、用到的依赖包

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>easyexcel</artifactId>
  4. <version>2.2.10</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>ooxml-schemas</artifactId>
  9. <version>1.4</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>javax.servlet</groupId>
  13. <artifactId>javax.servlet-api</artifactId>
  14. <version>4.0.1</version>
  15. <scope>provided</scope>
  16. </dependency>

二、封装工具类EasyExcelUtil

  1. package com.hkl.utils;
  2. import cn.hutool.core.date.DateUtil;
  3. import cn.hutool.core.date.TimeInterval;
  4. import cn.hutool.core.util.ObjectUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.alibaba.excel.EasyExcel;
  7. import com.alibaba.excel.ExcelReader;
  8. import com.alibaba.excel.ExcelWriter;
  9. import com.alibaba.excel.context.AnalysisContext;
  10. import com.alibaba.excel.enums.CellDataTypeEnum;
  11. import com.alibaba.excel.event.AnalysisEventListener;
  12. import com.alibaba.excel.metadata.CellData;
  13. import com.alibaba.excel.metadata.Head;
  14. import com.alibaba.excel.read.builder.ExcelReaderBuilder;
  15. import com.alibaba.excel.support.ExcelTypeEnum;
  16. import com.alibaba.excel.util.CollectionUtils;
  17. import com.alibaba.excel.write.metadata.WriteSheet;
  18. import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
  19. import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.apache.poi.ss.usermodel.Cell;
  22. import javax.servlet.http.HttpServletResponse;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.OutputStream;
  26. import java.net.URLEncoder;
  27. import java.util.ArrayList;
  28. import java.util.HashMap;
  29. import java.util.List;
  30. import java.util.Map;
  31. /**
  32. * <p>ClassName:EasyExcel工具类</p >
  33. * <p>Description:</p >
  34. * <p>Date:2021/9/1</p >
  35. */
  36. @Slf4j
  37. public class EasyExcelUtil {
  38. //-------------------------------------------------------------- 读取文件解析监听类 start ----------------------------------------------------
  39. /**
  40. * <p>ClassName:ExcelListener</p >
  41. * <p>Description:读取文件解析监听类,此类供外部实例化使用需要设置为静态类</p >
  42. * <p>Date:2021/9/2</p >
  43. */
  44. public static class ExcelListener<T> extends AnalysisEventListener<T>{
  45. /**
  46. * <p>存放读取后的数据</p >
  47. * @date 2021/9/2 0:10
  48. */
  49. public List<T> datas = new ArrayList<>();
  50. /**
  51. * <p>读取数据,一条一条读取</p >
  52. * @date 2021/9/2 0:15
  53. */
  54. @Override
  55. public void invoke(T t, AnalysisContext analysisContext) {
  56. datas.add(t);
  57. }
  58. /**
  59. * <p>解析完毕之后执行</p >
  60. * @date 2021/9/2 0:06
  61. */
  62. @Override
  63. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  64. log.info("读取数据条数:{}条!", datas.size());
  65. }
  66. public List<T> getDatas(){
  67. return this.datas;
  68. }
  69. }
  70. //-------------------------------------------------------------- 读取文件解析监听类 end ----------------------------------------------------
  71. //-------------------------------------------------------------- 导出excel表格,设置自适应列宽配置类 start ----------------------------------------------------
  72. /**
  73. * <p>ClassName:Custemhandler</p >
  74. * <p>Description:设置自适应列宽配置类</p >
  75. * <p>Date:2021/10/14</p >
  76. */
  77. public static class Custemhandler extends AbstractColumnWidthStyleStrategy {
  78. private static final int MAX_COLUMN_WIDTH = 255;
  79. //因为在自动列宽的过程中,有些设置地方让列宽显得紧凑,所以做出了个判断
  80. private static final int COLUMN_WIDTH = 20;
  81. private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);
  82. @Override
  83. protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
  84. boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
  85. if (needSetWidth) {
  86. Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());
  87. if (maxColumnWidthMap == null) {
  88. maxColumnWidthMap = new HashMap(16);
  89. CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
  90. }
  91. Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
  92. if (columnWidth >= 0) {
  93. if (columnWidth > MAX_COLUMN_WIDTH) {
  94. columnWidth = MAX_COLUMN_WIDTH;
  95. }else {
  96. if(columnWidth<COLUMN_WIDTH){
  97. columnWidth =columnWidth*2;
  98. }
  99. }
  100. Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());
  101. if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
  102. ((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);
  103. writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth* 256);
  104. }
  105. }
  106. }
  107. }
  108. private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
  109. if (isHead) {
  110. return cell.getStringCellValue().getBytes().length;
  111. } else {
  112. CellData cellData = (CellData)cellDataList.get(0);
  113. CellDataTypeEnum type = cellData.getType();
  114. if (type == null) {
  115. return -1;
  116. } else {
  117. switch(type) {
  118. case STRING:
  119. return cellData.getStringValue().getBytes().length;
  120. case BOOLEAN:
  121. return cellData.getBooleanValue().toString().getBytes().length;
  122. case NUMBER:
  123. return cellData.getNumberValue().toString().getBytes().length;
  124. default:
  125. return -1;
  126. }
  127. }
  128. }
  129. }
  130. }
  131. //-------------------------------------------------------------- 导出excel表格,设置自适应列宽配置类 end -----------------------------------------------------
  132. /**
  133. * <p> 读取Excel文件返回数据集合,不包含表头,默认读取第一个sheet数据 </p >
  134. * @date 2021/9/2 0:17
  135. * @param inputStream 输入流
  136. * @param tClass 数据映射类
  137. * @param excelListener 读取监听类
  138. * @return List 结果集
  139. */
  140. public static <T> List<T> readExcel(InputStream inputStream, Class<T> tClass, ExcelListener<T> excelListener){
  141. if(ObjectUtil.isNull(inputStream) || ObjectUtil.isNull(tClass) || ObjectUtil.isNull(excelListener)){
  142. return null;
  143. }
  144. ExcelReaderBuilder read = EasyExcel.read(inputStream, tClass, excelListener);
  145. read.sheet().doRead();
  146. return excelListener.getDatas();
  147. }
  148. /**
  149. * <p> 读取Excel文件返回数据集合,不包含表头,读取第x个sheet数据,不设置sheet就读取全部 </p >
  150. * @date 2021/9/2 0:17
  151. * @param inputStream 输入流
  152. * @param tClass 数据映射类
  153. * @param excelListener 读取监听类
  154. * @return List 结果集
  155. */
  156. public static <T> List<T> readExcel(InputStream inputStream, Integer sheetNo, Class<T> tClass, ExcelListener<T> excelListener){
  157. if(ObjectUtil.isNull(inputStream) || ObjectUtil.isNull(tClass) || ObjectUtil.isNull(excelListener)){
  158. return null;
  159. }
  160. ExcelReaderBuilder read = EasyExcel.read(inputStream, tClass, excelListener);
  161. if(ObjectUtil.isNotNull(sheetNo)){
  162. read.sheet(sheetNo).doRead();
  163. }else{
  164. ExcelReader excelReader = read.build();
  165. excelReader.readAll();
  166. excelReader.finish();
  167. }
  168. return excelListener.getDatas();
  169. }
  170. /**
  171. * <p>不带模板输出数据到Excel,数据传输类属性用 @ExcelProperty("") 标注</p >
  172. * @date 2021/9/2 0:32
  173. * @param response 响应对象
  174. * @param tClass 输出格式
  175. * @param datas 输出的数据
  176. * @return
  177. */
  178. public static <T> void writeEasyExcel(HttpServletResponse response, Class<T> tClass, List<T> datas, String fileName) throws IOException {
  179. TimeInterval timer = DateUtil.timer();
  180. if(ObjectUtil.isNull(response) || ObjectUtil.isNull(tClass)){
  181. return;
  182. }
  183. if(StrUtil.isBlank(fileName)){
  184. fileName = "excel.xlsx";
  185. }else{
  186. if(!fileName.contains(".xlsx")){
  187. fileName = fileName+".xlsx";
  188. }
  189. }
  190. response.setStatus(HttpServletResponse.SC_OK);
  191. response.setContentType("application/x-msdownload");
  192. response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName, "utf-8"));
  193. EasyExcel.write(response.getOutputStream(), tClass)
  194. .registerWriteHandler(new Custemhandler())
  195. .excelType(ExcelTypeEnum.XLSX)
  196. .sheet("sheet")
  197. .doWrite(datas);
  198. log.info("导出exlce数据:{}条,耗时:{}秒!", datas.size(), timer.intervalSecond());
  199. }
  200. /**
  201. * <p>带模板输出数据到Excel,数据传输类属性用 @ExcelProperty("") 标注</p >
  202. * @date 2021/9/2 0:32
  203. * @param outputStream 输出流
  204. * @param tClass 输出格式
  205. * @param datas 输出的数据
  206. * @return
  207. */
  208. public static <T> void writeExcel(InputStream inputStream ,OutputStream outputStream, Class<T> tClass, List<T> datas){
  209. TimeInterval timer = DateUtil.timer();
  210. if(ObjectUtil.isNull(outputStream) || ObjectUtil.isNull(tClass)){
  211. return;
  212. }
  213. // EasyExcel.write(outputStream, tClass).withTemplate(inputStream).sheet("sheet").doWrite(datas);
  214. EasyExcel.write(outputStream, tClass).excelType(ExcelTypeEnum.XLSX).withTemplate(inputStream).sheet("sheet").doFill(datas);
  215. log.info("导出exlce数据:{}条,耗时:{}秒!", datas.size(), timer.intervalSecond());
  216. }
  217. /**
  218. * <p>不带模板输出数据到Excel,数据传输类属性用 @ExcelProperty("") 标注</p >
  219. * @date 2021/9/2 0:32
  220. * @param response 响应对象
  221. * @param tClass 输出格式
  222. * @param datas 输出的数据
  223. * @return
  224. */
  225. public static <T> void writeExcel(HttpServletResponse response, Class<T> tClass, List<T> datas, String fileName) throws IOException, IllegalAccessException, NoSuchFieldException {
  226. TimeInterval timer = DateUtil.timer();
  227. if(ObjectUtil.isNull(response) || ObjectUtil.isNull(tClass)){
  228. return;
  229. }
  230. if(StrUtil.isBlank(fileName)){
  231. fileName = "excel.xlsx";
  232. }else{
  233. if(!fileName.contains(".xlsx")){
  234. fileName = fileName+".xlsx";
  235. }
  236. }
  237. //编码设置成UTF-8,excel文件格式为.xlsx
  238. response.setContentType("application/vnd.ms-excel");
  239. response.setCharacterEncoding("UTF-8");
  240. // 这里URLEncoder.encode可以防止中文乱码 和easyexcel本身没有关系
  241. fileName = URLEncoder.encode(fileName, "UTF-8");
  242. response.setHeader("Content-disposition", "attachment;filename=" + fileName);
  243. //处理注解转换
  244. // if(CollUtil.isNotEmpty(datas)){
  245. // for (T dataObj : datas) {
  246. // AnnotationUtil.resolveAnnotation(tClass, dataObj);
  247. // }
  248. // }
  249. ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), tClass).build();
  250. WriteSheet writeSheet = new WriteSheet();
  251. writeSheet.setSheetName("sheet");
  252. excelWriter.write(datas, writeSheet);
  253. excelWriter.finish();
  254. log.info("导出exlce数据:{}条,耗时:{}秒!", datas.size(), timer.intervalSecond());
  255. }
  256. }

工具类代码中, ExcelListener 为定义的内部监听类,需要继承 AnalysisEventListener,读取和写入方法分别为 readExcel 和 writeExcel,详见方法注释说明,直接复制到项目中即可使用

三、使用示例

1. 实体类

  1. package com.hkl.modules.dto;
  2. import com.alibaba.excel.annotation.ExcelProperty;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import java.io.Serializable;
  8. import java.math.BigDecimal;
  9. import java.util.Date;
  10. /**
  11. * <p>ClassName:ImportTestDatasReq</p >
  12. * <p>Description:</p >
  13. * <p>Date:2021/9/2</p >
  14. */
  15. @Data
  16. @AllArgsConstructor
  17. @NoArgsConstructor
  18. public class ImportTestDatasReq implements Serializable {
  19. @ExcelProperty(value = "userName")
  20. @ApiModelProperty("用户姓名")
  21. private String userName;
  22. @ExcelProperty(value = "address")
  23. @ApiModelProperty("地址")
  24. private String address;
  25. @ExcelProperty(value = "price")
  26. @ApiModelProperty("价格")
  27. private BigDecimal price;
  28. @ExcelProperty(value = "createDate")
  29. @ApiModelProperty("创建时间")
  30. private Date createDate;
  31. }

注意:实体类中不能使用链式写法注解 @Accessors(chain = true),否则会读取不到数据

2. 控制层

  1. @Slf4j
  2. @Api(tags = "Excel文件操作管理")
  3. @RestController
  4. @RequestMapping("/excel")
  5. public class ExcelController extends BaseController {
  6. /**
  7. * <p> MultipartFile 这个类一般是用来接收前台传过来的文件信息 </p >
  8. */
  9. @ApiOperation(value = "导入数据")
  10. @PostMapping("/importTestDatas")
  11. public CommonResult importTestDatas(@RequestParam("multipartFile") MultipartFile multipartFile) throws BizException, IOException {
  12. isBlank(multipartFile, "参数");
  13. List<ImportTestDatasReq> ImportTestDatasReqList = EasyExcelUtil.readExcel(multipartFile.getInputStream(), ImportTestDatasReq.class, new EasyExcelUtil.ExcelListener<>());
  14. ImportTestDatasReqList.forEach(System.out::println);
  15. return success(null);
  16. }
  17. @ApiOperation("导出")
  18. @GetMapping("/testExport")
  19. public void testExport(HttpServletResponse response) {
  20. try {
  21. List<ImportTestDatasReq> entities = 查询数据接口;
  22. EasyExcelUtil.writeEasyExcel(response, ImportTestDatasReq.class, entities, "列表导出");
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

注解说明:

1、@HeadRowHeight:设置表头高度,作用域在类

2、@ExcelIgnoreUnannotated:忽略没有注解标记的字段,作用域在类

3、@ExcelIgnore:忽略指定的字段,作用域在字段

4、@ExcelProperty:指定导出列名和索引,作用域在字段

5、@ColumnWidth:设置列的宽度,作用域在字段

6、@NumberFormat:设置数值精度,作用域在字段,例:@NumberFormat(value = "#.00")

7、@DateTimeFormat:格式化日期,作用域在字段,例:@DateTimeFormat(value = "yyyy-MM-dd")

注意:

1、我们可以使用 EasyExcel.write().registerWriteHandler(new Custemhandler()) 设置导出列的宽度为自适应,但是使用 registerWriteHandler(new Custemhandler()) 方法之后不能再使用注解@ColumnWidth,否则会导致自适应宽度不生效

2、BigDecimal 格式化标准模板为:#0.00。带千分位符为:,###,##0.00

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

闽ICP备14008679号