说明
前端采用 POST 传参, 后台可以可以进行传参鉴定
鉴定通过, 将二进制文件写入响应体, 否则将错误 json 信息写入响应体, 在前台展示提示信息
demo 代码如下:
// 前端代码
axios.post( "/exportData2ExcelDoc",
{name:"zhangsan"},
{responseType:"blob"} // 必不可少, 否则会乱码
).then(res => {
// 错误消息提示
if (res.data.obj == 'fail') {
this.$alert(res.data.msg, '提示', {type: "error"});
} else {
// 若没有错误提示, 则下载文件
const blob = new Blob([res.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob);
// 如果后端没有提供文件名不用管下面注释的代码
let contentDisposition = res.headers["content-disposition"]; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*"); // 正则匹配文件名
let result = patt.exec(contentDisposition);
let filename = decodeURI(result[1]);
downloadElement.style.display = "none";
downloadElement.href = href;
downloadElement.download = filename; //下载后文件名 ,也可以自定义
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
})
// java 端代码
@RequestMapping(value = "/exportData2ExcelDoc", method = RequestMethod.POST)
public ResultJson exportData2ExcelDoc(@RequestBody DataRcv dataRcv, HttpServletRequest request, HttpServletResponse response) {
ResultJson res = new ResultJson();
// fail 字符串为前台识别是否异常的标志词汇
res.setObj("fail");
if (dataRcv == null) {
res.setMsg("传参数据为空");
return res;
}
try {
// 查询数据
List<OriginData> originDataList = dataService.getData(dataRcv);
if (originDataList .size() < 1) {
res.setMsg("没有可导出的数据!");
return res;
}
// 准备数据
List<ExportExcelData> collect = originDataList .stream().map(ExportExcelData::convertData).collect(Collectors.toList());
String userAgent = request.getHeader("User-Agent");
String fileName = "数据导出(" + "备注" + ")" + System.currentTimeMillis() + ".xls"; // 文件的默认保存名
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
// 设置输出的格式
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
ServletOutputStream outputStream = response.getOutputStream();
// 生成 excel 文档
// EasyExcel.write(fileName, DnsProxyLogExportExcelData.class)
EasyExcel.write(outputStream, DnsProxyLogExportExcelData.class)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.sheet("数据导出")
.doWrite(collect);
return null;
} catch (Exception e) {
res.setMsg("系统繁忙, 请稍后再试");
e.printStackTrace();
}
return res;
}
// 工具类
@Data
public class ResultJson implements java.io.Serializable {
private static final long serialVersionUID = 6611660933038835116L;
private boolean success = false;// 是否成功
private String msg = "";// 提示信息
private Object obj = null;// 其他信息
}