pom

<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.1</version>

下载或导出Excel文件:只需要Excel对应的实体类 和 数据即可

Excel对应的实体类

@ContentRowHeight(20) // 内容的行高
@HeadRowHeight(20) // 表头的行高
//@ColumnWidth(60) // 列表的长度, 这个注解未起作用(可能是版本3.0.1的bug,如果有知道原因的小伙伴欢迎留言),后面我使用了自适应宽度的处理方式
@ContentStyle(dataFormat = 49) // 单元格格式
public class LeaveFLowConfigExcelDTO {// @ExcelIgnore // @ExcelProperty注解对应了Excel文件的列,value标识了表头名称,index标识了列索引,不建议同时使用value和index@ExcelProperty(value = {"部门"},index = 0)private String departmentName;@ExcelProperty(value = {"职位"},index = 1)private String positionNames;@ExcelProperty(value = {"上级"},index = 2)private String immediateSuperiorName;@ExcelProperty(value = {"工作会签"},index = 3)private String workHandover;@ExcelProperty(value = {"设备会签"},index = 4)private String equipmentHandover;@ExcelProperty(value = {"财务借款会签"},index = 5)private String financialLoanHandover;@ExcelProperty(value = {"财务发票会签"},index = 6)private String financialInvoiceHandover;@ExcelProperty(value = {"客户款项会签"},index = 7)private String customerServiceHandover;@ExcelProperty(value = {"退宿会签"},index = 8)private String checkOutHandover;@ExcelProperty(value = {"工牌会签"},index = 9)private String workCardHandover;@ExcelProperty(value = {"审批人"},index = 10)private String approvers;@ExcelProperty(value = {"抄送人"},index = 11)private String ccs;public LeaveFLowConfigExcelDTO() {}// get() set()方法: 注意不要使用build模式,否则easyExcel是解析不了的
}

下载/导出

 try {response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系String fileName = URLEncoder.encode("离职流程配置模板", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");// 头的策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 背景设置为蓝色headWriteCellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());// 字体
//            WriteFont headWriteFont = new WriteFont();
//            headWriteFont.setFontHeightInPoints((short)20); // 大小
//            headWriteFont.setBold(Boolean.TRUE); // 加粗
//            headWriteCellStyle.setWriteFont(headWriteFont);// 内容的策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//            contentWriteCellStyle.setWrapped(Boolean.TRUE); // 自动换行
//            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
//            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER); // 水平居中// 边框contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);contentWriteCellStyle.setBorderTop(BorderStyle.THIN);contentWriteCellStyle.setBorderRight(BorderStyle.THIN);contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);// 这里需要设置不关闭流EasyExcel.write(response.getOutputStream(), T).registerWriteHandler(new ColumnWidthStyleHandler()).registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle)).autoCloseStream(Boolean.FALSE).sheet().doWrite(data);} catch (Exception e) {// 重置responseresponse.reset();response.setContentType("application/json");response.setCharacterEncoding("utf-8");Map<String, String> map = new HashMap<String, String>();map.put("status", "failure");map.put("message", "下载文件失败" + e.getMessage());response.getWriter().println(JSON.toJSONString(map));
}private List<LeaveFLowConfigExcelDTO> data() {List<LeaveFLowConfigExcelDTO> list = new ArrayList<>();for (int i = 0; i < 1; i++) {LeaveFLowConfigExcelDTO excelDTO = new LeaveFLowConfigExcelDTO();excelDTO.setDepartmentName("部门名称(必填)");excelDTO.setPositionNames("职位(非必填,多个逗号隔开)");excelDTO.setImmediateSuperiorName("工号(非必填)");excelDTO.setWorkHandover("直属上级或工号(必填)");excelDTO.setEquipmentHandover("直属上级或工号(必填)");excelDTO.setFinancialLoanHandover("直属上级或工号(必填)");excelDTO.setFinancialInvoiceHandover("直属上级或工号(必填)");excelDTO.setCustomerServiceHandover("直属上级或工号(必填)");excelDTO.setCheckOutHandover("直属上级或工号(非必填)");excelDTO.setWorkCardHandover("直属上级或工号(必填)");excelDTO.setEquipmentHandover("直属上级或工号(必填)");excelDTO.setApprovers("工号(非必填,多个逗号隔开)");excelDTO.setCcs("工号(非必填,多个逗号隔开)");list.add(excelDTO);}return list;
}// 自定义的处理器,使导出的excel列宽自适应. (easyExcel列宽自适应还存在一定的缺陷,对英文和数字的支持不太友好)
public class ColumnWidthStyleHandler extends AbstractColumnWidthStyleStrategy {private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();@Overrideprotected void setColumnWidth(CellWriteHandlerContext context) {boolean neesSetWidth = context.getHead() || !CollectionUtils.isEmpty(context.getCellDataList());if (neesSetWidth){// context.getWriteSheetHolder().getSheet().setColumnWidth(context.getCell().getColumnIndex(), columnWidth * 256); // 可以直接把宽度写死Map<Integer, Integer> maxColumnWidthMap = CACHE.get(context.getWriteSheetHolder().getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap<>();CACHE.put(context.getWriteSheetHolder().getSheetNo(), maxColumnWidthMap);}Integer columnWidth = this.dataLength(context.getCellDataList(), context.getCell(), context.getHead());if (columnWidth >= 0) {if (columnWidth > 255) {columnWidth = 255;}Integer maxColumnWidth = maxColumnWidthMap.get(context.getCell().getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {maxColumnWidthMap.put(context.getCell().getColumnIndex(), columnWidth);context.getWriteSheetHolder().getSheet().setColumnWidth(context.getCell().getColumnIndex(), columnWidth * 256);}}}}private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData cellData = cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch (type) {case STRING:return cellData.getStringValue().getBytes().length;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}
}

导入Excel文件

EasyExcel.read(file.getInputStream(),  // file类型:MultipartFile LeaveFLowConfigExcelDTO.class, new LeaveFlowConfigExcelListener(this,flowService,sysAccountService,dictionaryService,sysDepartmentService)) //导入的时候需要监听器处理,监听器会一行行读取,此时你可以选择一行行处理数据 或 读取多行后再批处理.sheet().doRead();// 监听器
public class LeaveFlowConfigExcelListener extends AnalysisEventListener<LeaveFLowConfigExcelDTO> {private static final Logger   LOGGER              = LoggerFactory.getLogger(LeaveFlowConfigExcelListener.class);private ILeaveService         leaveService;private IFlowService          flowService;private ISysAccountService    sysAccountService;private IDictionaryService    dictionaryService;private ISysDepartmentService sysDepartmentService;public LeaveFlowConfigExcelListener() {}// 监听器是无法被注入到IOC容器的,所以也无法通过@Autowired注入服务,只能通过构造方法传入public LeaveFlowConfigExcelListener(ILeaveService leaveService, IFlowService flowService, ISysAccountService sysAccountService, IDictionaryService dictionaryService,ISysDepartmentService sysDepartmentService) {this.leaveService = leaveService;this.flowService = flowService;this.sysAccountService = sysAccountService;this.dictionaryService = dictionaryService;this.sysDepartmentService = sysDepartmentService;}@Overridepublic void invoke(LeaveFLowConfigExcelDTO data, AnalysisContext context) {LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));// ......}/*** 所有数据解析完成了 都会来调用** @param context*/@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {LOGGER.info("excel数据解析完成,开始存储");// ......}}

单元格格式参考值

private static final String[] BUILTIN_FORMATS_CN = {// 0"General",// 1"0",// 2"0.00",// 3"#,##0",// 4"#,##0.00",// 5"\"¥\"#,##0_);(\"¥\"#,##0)",// 6"\"¥\"#,##0_);[Red](\"¥\"#,##0)",// 7"\"¥\"#,##0.00_);(\"¥\"#,##0.00)",// 8"\"¥\"#,##0.00_);[Red](\"¥\"#,##0.00)",// 9"0%",// 10"0.00%",// 11"0.00E+00",// 12"# ?/?",// 13"# ??/??",// 14// The official documentation shows "m/d/yy", but the actual test is "yyyy/m/d"."yyyy/m/d",// 15"d-mmm-yy",// 16"d-mmm",// 17"mmm-yy",// 18"h:mm AM/PM",// 19"h:mm:ss AM/PM",// 20"h:mm",// 21"h:mm:ss",// 22// The official documentation shows "m/d/yy h:mm", but the actual test is "yyyy-m-d h:mm"."yyyy-m-d h:mm",// 23-26 No specific correspondence found in the official documentation.// 23null,// 24null,// 25null,// 26null,// 27"yyyy\"年\"m\"月\"",// 28"m\"月\"d\"日\"",// 29"m\"月\"d\"日\"",// 30"m-d-yy",// 31"yyyy\"年\"m\"月\"d\"日\"",// 32"h\"时\"mm\"分\"",// 33"h\"时\"mm\"分\"ss\"秒\"",// 34"上午/下午h\"时\"mm\"分\"",// 35"上午/下午h\"时\"mm\"分\"ss\"秒\"",// 36"yyyy\"年\"m\"月\"",// 37"#,##0_);(#,##0)",// 38"#,##0_);[Red](#,##0)",// 39"#,##0.00_);(#,##0.00)",// 40"#,##0.00_);[Red](#,##0.00)",// 41"_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)",// 42"_(\"¥\"* #,##0_);_(\"¥\"* (#,##0);_(\"¥\"* \"-\"_);_(@_)",// 43"_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)",// 44"_(\"¥\"* #,##0.00_);_(\"¥\"* (#,##0.00);_(\"¥\"* \"-\"??_);_(@_)",// 45"mm:ss",// 46"[h]:mm:ss",// 47"mm:ss.0",// 48"##0.0E+0",// 49"@",// 50"yyyy\"年\"m\"月\"",// 51"m\"月\"d\"日\"",// 52"yyyy\"年\"m\"月\"",// 53"m\"月\"d\"日\"",// 54"m\"月\"d\"日\"",// 55"上午/下午h\"时\"mm\"分\"",// 56"上午/下午h\"时\"mm\"分\"ss\"秒\"",// 57"yyyy\"年\"m\"月\"",// 58"m\"月\"d\"日\"",// 59"t0",// 60"t0.00",// 61"t#,##0",// 62"t#,##0.00",// 63-66 No specific correspondence found in the official documentation.// 63null,// 64null,// 65null,// 66null,// 67"t0%",// 68"t0.00%",// 69"t# ?/?",// 70"t# ??/??",// 71"ว/ด/ปปปป",// 72"ว-ดดด-ปป",// 73"ว-ดดด",// 74"ดดด-ปป",// 75"ช:นน",// 76"ช:นน:ทท",// 77"ว/ด/ปปปป ช:นน",// 78"นน:ทท",// 79"[ช]:นน:ทท",// 80"นน:ทท.0",// 81"d/m/bb",// end};

easyExcel下载或导出相关推荐

  1. 阿里easyexcel通过模板导出excel

    easyexcel通过模板导出excel 之前使用其他方式进行excel的导出,像poi或者freemarker或者Beetl,效果都还行,但是总是有一些小问题.许多的解决思路都是:通过制作excel ...

  2. easyexcel下载工具

    优化excel下载功能,采用新的工具类降低内存: https://github.com/alibaba/easyexcel pom: <!-- easyexcel依赖包 --> <d ...

  3. EasyExcel通过模板导出数据

    EasyExcel通过模板导出数据 大家好,这两天在做excel导出功能,使用的是easyExcel,不得不说其功能全面,很好入手. 但是在开发的过程中也会遇到一些文档里无法提供解决的问题,这里我分享 ...

  4. java使用EasyExcel实现导入导出几种方式(导入、模板导出、和不需要模板的导出)

    java通过EasyExcel实现导入导出(导入.模板导出.和不需要模板的导出) 此文章只是涉及到简单的导入导出 通过实体模板导入数据 无实体模板导入数据 导出数据 通过模板导出数据 使用到的mave ...

  5. easyexcel复杂模板导出(合并行列,列统计汇总)

    easyexcel复杂模板导出(合并行列,统计汇总) 为什么使用easyexcel 1. easyexcel可以通过模板导出(符合项目使用习惯) 2. easyexcel支持大数据量导出,性能较好(满 ...

  6. 得到app文稿导出_得到app的文稿怎么下载复制导出

    得到app的课程文稿怎么下载复制导出 决策的对错关系到战争的成败,所以<孙子兵法>强调 "知敌之情' 因为情报信息是决策的依据.作为一个企业决策者,其决策 也绝不能凭空臆断,而应 ...

  7. easyexcel结合zip 导出压缩文件(包含多个excel)

    easyexcel结合zip 导出压缩文件(包含多个excel) 直接上代码- 分批次查询处理示例代码 int limit = 1;int pageNum = 500;ByteArrayOutputS ...

  8. 使用EasyExcel下载,文件名乱码问题处理

    使用阿里EasyExcel下载excle的简单样例记录,包含前后端核心代码,主要记录中文文件名称乱码问题的处理. EasyExcle的使用不再多做记录,EasyExcel教程-阿里云开发者社区 (al ...

  9. easyexcel使用教程-导出篇

    easyExcel使用教程–导出篇 开始准备工作 1.导入Maven依赖 <dependency><groupId>com.alibaba</groupId>< ...

最新文章

  1. nginx将泛解析的匹配域名绑定到子目录配置方法
  2. LeetCode-笔记-143. 重排链表
  3. 使用fiddler4做代理调试手机页面
  4. EOS 源代码解读 (2)插件-流程
  5. 各种语言速度之比,实验验证Cgojuliajavapythonoctave
  6. ASCII码、HEX、字符、BCD 等等 基础知识思考
  7. c++客户端发送加锁_MySQL语句加锁分析详解
  8. spring datasource oracle,spring中2种oracle数据源的配置
  9. 力扣77.组合(JavaScript)
  10. 17R-无重复数字的三位数和去重后最大数
  11. python声明匿名函数_举例讲解Python的lambda语句声明匿名函数的用法
  12. iOS 无线打印功能(AirPrint)
  13. 清理谷歌浏览器注册表_将谷歌浏览器的注册表彻底删除的方法
  14. 问卷调查:自定义表单设计vue
  15. R语言数据的排序、转换、汇总
  16. 怎样用python中matplotlib模块直观的将股票数据展现出来
  17. 用计算机弹起风了歌词,买辣椒也用券
  18. 开关稳压电源软件设计
  19. CAD文件版本怎么转换?如何将高版本转换成低版本?
  20. 树莓派Pico直流电机接口技术及PWM电机调速控制MicroPython编程

热门文章

  1. 关于微信公众号文章抓取
  2. FOCUS projects 5 Pro(照片景深处理软件)官方正式版V5.34.03722 | 景深合成软件下载
  3. Python绘制K线图之可视化神器pyecharts
  4. 移动端-K线图-开发
  5. 基于FPGA的双通道DDS信号发生器
  6. Q上多项式可约性深化定理
  7. 深入理解java虚拟机(五)GC垃圾回收-经典垃圾收集器
  8. 3d计算机原理,3d的技术原理有哪些
  9. 由于高精度事件计时器(HPET)驱动过时导致AMD机器装Win10的卡死蓝屏问题记录
  10. 2021-08-11 WPF控件专题 Frame 控件详解