1. 先导入EasyExcel依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
2. 给实体类上注解,标注导出的excel的表头属性,以及标注无需导出的实体属性
@ExcelProperty("表头单元格名称") // 标注在需要导出的实体属性上
@ExcelIgnore // 标注在无需导出的实体属性上
3. 写后端excel导出通用方法
/**
* 导出excel
* @param list 需要导出的数据
*/
public static <T> void exportExcel(List<T> list, Class<T> clazz) {
ServletOutputStream outputStream;
try {
HttpServletResponse response = ServletUtils.getResponse();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
outputStream = response.getOutputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
// easyExcel导出的核心代码
EasyExcel.write(outputStream)
.head(clazz)
.excelType(ExcelTypeEnum.XLSX)
.sheet()
.doWrite(list);
}
4. 控制器简单编写示例
/**
* 导出字典类型excel
*/
@LogAnnotation(title = "导出字典表格", operateType = OperateType.EXPORT)
@ApiOperation("导出字典类型excel表格")
@PostMapping(value = "/exportDictTypeExcel")
public void exportDictTypeExcel(@RequestBody List<Long> dictTypeIdList){
List<DictTypeEntity> dictTypeEntityList = dictTypeDao.selectBatchIds(dictTypeIdList);
ExcelUtils.exportExcel(dictTypeEntityList, DictTypeEntity.class);
}
5. 前端vue的请求方法
js请求方法代码,需要加上responseType:'blob'
export function exportDictTypeExcel(data) {
return request({
url: '/system/dicttype/exportDictTypeExcel',
method: 'post',
data,
responseType:'blob'
})
}
vue请求方法代码
exportDict() {
var arr = [];
this.multipleSelection.forEach((row) => arr.push(row.dictId));
if (arr.length === 0) {
this.$message({
message: "请选择要导出的数据。",
type: "error",
});
} else {
this.$confirm("确定导出吗", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "success",
callback: (action) => {
if (action === "confirm") {
//批量导出
exportDictTypeExcel(arr).then((res) => {
});
}
},
});
}
},
6. 如果写完以上代码,前后端都能跑通,并且已经有响应的二进制编码,浏览器就是不弹出excel文件下载的弹框,找到你vue的request.js文件,看看请求是否被拦截,
如果被拦截,加上以下代码,即可实现excel导出文件下载的弹框
const contentType = response.headers['content-type'];
if (contentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8") {
let blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
let url = window.URL.createObjectURL(blob);
const link = document.createElement('a'); // 创建a标签
link.href = url;
// link.download = 'test.xlsx';
link.click();
URL.revokeObjectURL(url); // 释放内存
return
}
标签:arr,Vue,SpringBoot,exportDictTypeExcel,导出,EasyExcel,excel,blob,response
From: https://www.cnblogs.com/18sui/p/17234333.html