在实现的过程中遇到过以下问题:
换成.xls后,又变成这样!
最终,问题终于得到了解决
上代码!
前端($http是二次封装的axios,不用在意,直接axios也可!)
doDownload() {
this.$http({
url: this.$url.downloadTemplate,
method: 'get',
responseType: 'blob' // blob 或 arraybuffer
}).then(res => {
if(res) {
this.downloadFile(res?.data, '用户模板.xlsx');
}
}).catch(e => {
console.log(e);
})
},
// 下载文件
downloadFile(res, fileName) {
let blob = new Blob([res]); //res为从后台返回的数据
if (!fileName) {
fileName = res.headers['content-disposition'].split('filename=').pop();
}
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
}
}
后端
DO实体类(要与数据库字段对应)
@Data
@ExcelIgnoreUnannotated
public class UserDO {
@ColumnWidth(20)
@ExcelIgnore
private String uuid;
@ExcelProperty(value = {"用户名"}, index = 0)
@ColumnWidth(20)
private String account;
@ExcelProperty(value = {"密码"}, index = 1)
@ColumnWidth(20)
private String pwd;
@ExcelProperty(value = {"角色"}, index = 2)
@ColumnWidth(20)
private String identity;
@ColumnWidth(20)
@ExcelIgnore
private String toDel;
}
Controller
@GetMapping("/download")
public void downloadExcl(HttpServletResponse response) {
userService.downloadExcl(response);
}
ServiceImpl,(这里.doWrite()是写入对应列的数据,不是标题名)
@Override
public void downloadExcl(HttpServletResponse response) {
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("用户列表", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()).head(UserDO.class).excelType(ExcelTypeEnum.XLSX).sheet("用户列表").doWrite(new ArrayList<>());
} catch (Exception e) {
}
}
pom.xml(选择版本的问题,要参考官网)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
注:版本爆红问题,参考IDEA中pom.xml配置文件依赖文件版本号报红的最有效解决办法_pom.xml文件报红_Butterfly_ren的博客-CSDN博客
如果还是爆红,先不要像一些教程说的,调配置setting等...,先重启idea这种的操作看看。
(这里复制粘贴,可能version爆红,在那里就好使,我也不知道为什么,有大佬知道麻烦评论区解释一下)
最终结果图
然后说说上面遇到的问题,
这里之有.xlsx是没问题的,但换成.xls,虽然能够正常显示,但会报不匹配问题。
这里参考的:Java使用EasyExcel下载xls、xlsx 出现文件格式与扩展名不匹配_文件格式和扩展名不匹配 easyexcel导出_小 肥羊的博客-CSDN博客
至于.xls的问题,本人还没有解决,如果哪位大佬有解决方法,希望能够分享一下!