【源码】JeecgBoot导出Excel模板
版权声明:文为博主原创文章,未经博主允许不得转载。原创不易,希望大家尊重原创!
Copyright © 2026 DarLing丶张皇 保留所有权利
一、前言
JeecgBoot中Autopoi是其自带的实现导入导出功能的poi,可以方便我们更简单的实现Excel模板导出,Excel导入,Word模板导出。
使用前准备:在Maven中引入Autopoi依赖
java
<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
java
// 引入模板文件存放地址
@Value(value = "${jeecg.path.template-attendance-record-file}")
private String templateAttendanceRecordFile;
/**
* 导出考勤记录表Excel(模板)
* templateAttendanceRecordFile为模板存放路径,请在yml文件中配置
* @param startTime
* @param endTime
*/
@GetMapping(value = "/export-excel-file")
public ResponseEntity<Resource> exportExcel(@RequestParam(name="startTime",required=true) String startTime, @RequestParam(name="endTime",required=true) String endTime) {
Resource resource = null;
File tempFile = null;
try {
// step.1 获取数据,并写入Excel,调用Service层导出方法
org.apache.poi.ss.usermodel.Workbook workbook = tbClockRecordService.exportExcel(startTime, entTime, templateAttendanceRecordFile);
// step.2 创建临时文件保存导出结果
tempFile = File.createTempFile("exported_survey_report_sample_test_file", ".xlsx");
FileOutputStream fos = new FileOutputStream(tempFile);
workbook.write(fos);
fos.close();
workbook.close();
// step.3 创建FileSystemResource对象
resource = new FileSystemResource(tempFile);
// step.4 返回ResponseEntity,包含文件的响应
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=attendance_record.xlsx")
.body(resource);
} catch (Exception e) {
e.printStackTrace();
log.error("考勤信息导出失败" + e.getMessage());
throw new ValidationException("考勤信息失败:" + e.getMessage());
} finally {
// 清理临时文件(可选,取决于是否需要保留文件)
if (tempFile != null && tempFile.exists()) {
tempFile.deleteOnExit();
}
}
}
Service
java
/**
* 导出考勤信息Excel(模板)
* @param startTime 开始时间
* @param endTime 结束时间
* @param templatePath 模板地址路径
* @return
*/
Workbook exportExcel(String startTime, String endTime, String templatePath);
5、ServiceImpl
java
/**
* 导出考勤记录Excel(模板)
* @param startTime 开始时间
* @param entTime 结束时间
* @param templatePath 模板地址路径
* @return
*/
@Override
public Workbook exportExcel(String startTime, String entTime, String templatePath){
Workbook workbook = null;
try {
// Step.1、判断模板文件是否存在
File templateFile = new File(templatePath);
if (!templateFile.exists()){
throw new IOException("模板文件不存在:" + templatePath);
}
// Step.2、数据查询(仅为示例)
List<TbClockRecord> tbClockRecordList = tbClockRecordService.selectList(
new LambdaQueryWrapper<AreaFarm>()
.eq(TbClockRecord ::getCreateTime, startTime)
.eq(TbClockRecord ::getCreateTime, entTime)
);
if (ObjectUtil.isNull(tbLeave )){
throw new JeecgBootException("未找到数据!");
}
// Step.3、封装模板数据(以下仅为示例,具体数据请根据自身业务赋值)
List<Map<String, Object>> totalMapList = new ArrayList<>();
List<Map<String, Object>> listMap = new ArrayList<>();
// 序号,从1自增
int seqNum = 1;
for (TbClockRecord tbClockRecord : tbClockRecordList) {
Map<String, Object> map = new HashMap<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模板导出Excel
TemplateExportParams params = new TemplateExportParams(templatePath);
workbook = ExcelExportUtil.exportExcel(params, totalMapList);
} catch (Exception e) {
e.printStackTrace();
}
return workbook;
}
4、前端调取方法
4.1、统一的API请求管理
javascript
/**
* 下载文件 用于导出
* @param url 请求地址
* @param parameter 请求参数
* @returns {*}
*/
export function downFile(url,parameter){
return axios({
url: url,
params: parameter,
method:'get' ,
responseType: 'blob'
})
}
//get请求、post请求等此处省略
4.2、请求
javascript
// 引入API请求
import { downFile } from '@/api';
/**
* 下载文件 用于Excel导出
* @param record 导出数据的行信息
* @returns {*}
*/
handleExportWord(record){
const { id, name } = record;
let params = { id };
downFile("/export-excel-file", params).then((data)=>{
if (!data || data.size === 0) {
this.$message.warning('考勤记录表下载失败!');
return;
}
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE/Edge 浏览器
window.navigator.msSaveBlob(
new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
fileName + '.xlsx'
);
} else {
// 现代浏览器
let url = window.URL.createObjectURL(
new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', fileName + '-考勤记录表.xlsx'); // 统一使用 fileName
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}
})
.finally(() => {
this.confirmLoading = false;
})
})
}
三、说明
预先设置导出模板,通过表达式取值,实现一些特殊样式/风格的导出,避免编写大量复杂的代码,降低开发难度,提高维护效率
word模板和Excel模板用法基本一致,支持的标签也是一致的,若需要Word模版导出,请移步前往【源码】JeecgBoot导出Word模板学习。
Excel模板导出:前往JeecgBoot文档中心参考。
原创不易,喝水莫忘挖井人,谢谢!!!