当前位置: 首页 > news >正文

【源码】JeecgBoot导出Excel模板

【源码】JeecgBoot导出Excel模板

  • 一、前言
    • 1、Excel模板原型
  • 二、实现代码
    • 1、导入模板
    • 2、yml文件配置
    • 3、接口方法
    • 4、前端调取方法
  • 三、说明

版权声明:文为博主原创文章,未经博主允许不得转载。原创不易,希望大家尊重原创!
Copyright © 2026 DarLing丶张皇 保留所有权利

一、前言

JeecgBoot中Autopoi是其自带的实现导入导出功能的poi,可以方便我们更简单的实现Excel模板导出,Excel导入,Word模板导出。

使用前准备:在Maven中引入Autopoi依赖

<dependency><groupId>org.jeecgframework</groupId><artifactId>autopoi-web</artifactId><version>1.3.6</version></dependency>

所有表达式

表达式描述/示例
三目运算{{test ? obj:obj2}}test如果某一个字段,则该字段一定是布尔类型,如果一个表达式,如arg == 1则一定要带有空格
n:这个cell是数值类型 {{n:}}
le:代表长度{{le:()}} 在if/else 运用{{le:() > 8 ? obj1 : obj2}}
fd:格式化时间 {{fd:(obj;yyyy-MM-dd)}}
fn:格式化数字 {{fn:(obj;###.00)}}
fe:遍历数据,创建row
!fe遍历数据不创建row
$fe:下移插入,把当前行,下面的行全部下移.size()行,然后插入
#fe:横向遍历
v_fe:横向遍历值
!if:删除当前列 {{!if:(test)}}
单引号表示常量值 ‘’ 比如’1’ 那么输出的就是 1
&NULL&空格
]]换行符 多行遍历导出

1、Excel模板原型

上图中:t.name等为模板占位符,预先设置导出模板,通过表达式取值

二、实现代码

1、导入模板

先将模板Word导入到jeecg-boot-module-system>src>main>resources>templates

2、yml文件配置

统一在.yml文件中配置文档模板目录,方便维护
2.1、开发环境下,在application-dev.yml中配置:

path :
template-attendance-record-file: jeecg-boot-module-system/src/main/resources/templates/attendance_record.xlsx

2.2、生产环境下,在application-prod.yml中配置:

path :
template-attendance-record-file: jeecg-boot-module-system/src/main/resources/templates/attendance_record.xlsx

3、接口方法

Controller

// 引入模板文件存放地址@Value(value="${jeecg.path.template-attendance-record-file}")privateStringtemplateAttendanceRecordFile;/** * 导出考勤记录表Excel(模板) * templateAttendanceRecordFile为模板存放路径,请在yml文件中配置 * @param startTime * @param endTime */@GetMapping(value="/export-excel-file")publicResponseEntity<Resource>exportExcel(@RequestParam(name="startTime",required=true)StringstartTime,@RequestParam(name="endTime",required=true)StringendTime){Resourceresource=null;FiletempFile=null;try{// step.1 获取数据,并写入Excel,调用Service层导出方法org.apache.poi.ss.usermodel.Workbookworkbook=tbClockRecordService.exportExcel(startTime,entTime,templateAttendanceRecordFile);// step.2 创建临时文件保存导出结果tempFile=File.createTempFile("exported_survey_report_sample_test_file",".xlsx");FileOutputStreamfos=newFileOutputStream(tempFile);workbook.write(fos);fos.close();workbook.close();// step.3 创建FileSystemResource对象resource=newFileSystemResource(tempFile);// step.4 返回ResponseEntity,包含文件的响应returnResponseEntity.ok().header("Content-Disposition","attachment; filename=attendance_record.xlsx").body(resource);}catch(Exceptione){e.printStackTrace();log.error("考勤信息导出失败"+e.getMessage());thrownewValidationException("考勤信息失败:"+e.getMessage());}finally{// 清理临时文件(可选,取决于是否需要保留文件)if(tempFile!=null&&tempFile.exists()){tempFile.deleteOnExit();}}}

Service

/** * 导出考勤信息Excel(模板) * @param startTime 开始时间 * @param endTime 结束时间 * @param templatePath 模板地址路径 * @return */WorkbookexportExcel(StringstartTime,StringendTime,StringtemplatePath);

5、ServiceImpl

/** * 导出考勤记录Excel(模板) * @param startTime 开始时间 * @param entTime 结束时间 * @param templatePath 模板地址路径 * @return */@OverridepublicWorkbookexportExcel(StringstartTime,StringentTime,StringtemplatePath){Workbookworkbook=null;try{// Step.1、判断模板文件是否存在FiletemplateFile=newFile(templatePath);if(!templateFile.exists()){thrownewIOException("模板文件不存在:"+templatePath);}// Step.2、数据查询(仅为示例)List<TbClockRecord>tbClockRecordList=tbClockRecordService.selectList(newLambdaQueryWrapper<AreaFarm>().eq(TbClockRecord::getCreateTime,startTime).eq(TbClockRecord::getCreateTime,entTime));if(ObjectUtil.isNull(tbLeave)){thrownewJeecgBootException("未找到数据!");}// Step.3、封装模板数据(以下仅为示例,具体数据请根据自身业务赋值)List<Map<String,Object>>totalMapList=newArrayList<>();List<Map<String,Object>>listMap=newArrayList<>();// 序号,从1自增intseqNum=1;for(TbClockRecordtbClockRecord:tbClockRecordList){Map<String,Object>map=newHashMap<String,Object>();// 序号map.put("xh",seqNum);// 姓名map.put("name",tbClockRecord.getName());// 部门map.put("dept",tbClockRecord.getDept());// 上班打卡map.put("clockin",tbClockRecord.getClockin());// 下班打卡map.put("clockout",tbClockRecord.getClockout());// 打卡说明map.put("detail",tbClockRecord.getDetail());// 备注map.put("remark",tbClockRecord.getRemark());seqNum++;listMap.add(map);}totalMapList.put("maplist",listMap)// Step.4、使用Jeecg-Boot模板导出ExcelTemplateExportParamsparams=newTemplateExportParams(templatePath);workbook=ExcelExportUtil.exportExcel(params,totalMapList);}catch(Exceptione){e.printStackTrace();}returnworkbook;}

4、前端调取方法

4.1、统一的API请求管理

/** * 下载文件 用于导出 * @param url 请求地址 * @param parameter 请求参数 * @returns {*} */exportfunctiondownFile(url,parameter){returnaxios({url:url,params:parameter,method:'get',responseType:'blob'})}//get请求、post请求等此处省略

4.2、请求

// 引入API请求import{downFile}from'@/api';/** * 下载文件 用于Excel导出 * @param record 导出数据的行信息 * @returns {*} */handleExportWord(record){const{id,name}=record;letparams={id};downFile("/export-excel-file",params).then((data)=>{if(!data||data.size===0){this.$message.warning('考勤记录表下载失败!');return;}if(typeofwindow.navigator.msSaveBlob!=='undefined'){// IE/Edge 浏览器window.navigator.msSaveBlob(newBlob([data],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),fileName+'.xlsx');}else{// 现代浏览器leturl=window.URL.createObjectURL(newBlob([data],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));letlink=document.createElement('a');link.style.display='none';link.href=url;link.setAttribute('download',fileName+'-考勤记录表.xlsx');// 统一使用 fileNamedocument.body.appendChild(link);link.click();document.body.removeChild(link);window.URL.revokeObjectURL(url);}}).finally(()=>{this.confirmLoading=false;})})}

三、说明

预先设置导出模板,通过表达式取值,实现一些特殊样式/风格的导出,避免编写大量复杂的代码,降低开发难度,提高维护效率
word模板和Excel模板用法基本一致,支持的标签也是一致的,若需要Word模版导出,请移步前往【源码】JeecgBoot导出Word模板学习。
Excel模板导出:前往JeecgBoot文档中心参考。

原创不易,喝水莫忘挖井人,谢谢!!!

http://www.jsqmd.com/news/1288868/

相关文章:

  • 浅谈智慧路灯APP开发有哪些好处
  • 校园运维系统轻量化改造:基于零代码搭建校园报修管理平台落地实践
  • 2026年度滚筒喷砂机厂家值得信赖TOP6榜单 - 资讯在线
  • CircleType.js完全指南:如何在网页中轻松实现文字曲线效果
  • ThreeJS Water:5分钟打造惊艳的3D水面效果,让网页“活“起来
  • 专科生论文写作必备:8款AI工具提升质量与通过率
  • 如何安装Pecan?5分钟快速上手macOS实用菜单栏工具
  • 文生图Prompt怎么写:把模糊创意拆成七个可控要素
  • 环曜Agent 本地化知识库部署实战:Ollama + RAGFlow 私有化 RAG 踩坑记录
  • 3个步骤让你的华硕笔记本告别卡顿:G-Helper轻量级控制工具实战指南
  • UniRig:基于自回归Transformer的统一骨骼绑定框架,实现跨物种3D模型自动化骨骼生成与蒙皮权重预测
  • Gscript CLI命令完全手册:掌握编译、调试与混淆的终极技巧
  • norns音频路由完全指南:从Tape录音到效果链处理的高效工作流
  • Latest ADB Fastboot Installer常见问题解答:从下载到使用全攻略
  • 揭秘Ninjabrain-Bot核心算法:贝叶斯推断如何革新末地城定位
  • 为什么92%的AI基金组合在实盘中失效?——穿透式拆解特征工程、过拟合陷阱与黑箱决策盲区
  • Faraday漏洞管理平台监控与日志分析实战:从部署到优化的10个核心技巧
  • 从理论到实践:Geotorch约束优化的数学原理与代码实现
  • 单片机毕设项目:基于单片机的环境数据采集智能窗帘控制系统实现 基于 STC89C52 的多模式智能窗帘硬件控制系统设计(011501)
  • 牙周炎结构免疫研究:PCF如何观察上皮、免疫细胞和微生物信号的空间关系
  • 数据科学实战:特征工程与数据预处理核心技巧
  • ArcGIS教程下载安装教程【超详细】保姆级图文教程(附安装包)
  • Instaclone核心功能解析:从用户认证到实时通知的实现原理
  • Adobe-GenP 3.0:免费解锁Adobe创意云软件的三步终极指南
  • 从Vim到Emacs:Oh My Emacs的Evil模式让你无缝过渡
  • 网盘直链下载助手:告别客户端限制,三步获取真实下载链接
  • OpenClaw助力端侧智能再升级: 软通动力从感知到行动的全栈智能变革
  • XCOM2模组管理终极解决方案:AML启动器完整指南
  • 如何用Pixelle-Video在3分钟内制作专业级短视频?AI全自动引擎完全指南
  • 接入ailog 看android设备的实时日志并解析