1
我在使用javascript导出表格时遇到问题。后端是春天,我在控制器中的方法看起来像这样。从服务器中导出excel表格中的javascript
@PostMapping(produces = "application/vnd.ms-excel")
public void report(@RequestBody @Validated final ReportRequest reportRequest, final HttpServletResponse response, final Principal principal) {
log.info("'{}' Requested report '{}'", principal.getName(), reportRequest);
final List<Data> dataList = dataRepository.findAll(
findByCriteria(
reportRequest.getFilterDatas(),
reportRequest.getId(),
reportRequest.getStartDate(),
reportRequest.getEndDate()));
final SXSSFWorkbook workbook = excelService.generateExcelFromDraData(dataList, FILE_NAME);
writeToOutputStream(response, workbook);
}
在前端我使用vue.js和axios为http客户端。而导出方法是:
axios.post(
url+'report',
query,
{headers: {
"Access-Control-Allow-Headers" : "*",
"X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')
}
}
)
.then((response) => {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var blob = new Blob([response.data], {type: "application/vnd.ms-excel"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'report.xlsx';
a.click();
window.URL.revokeObjectURL(url);
}, (error) => {
}
)
当我用邮递员打'发送和下载'时,我得到了我想要的excel。但是,当我从客户端做到这一点时,我在console.log中获得响应字节,但是我无法打开excel,因为文件格式或文件扩展名无效,因此'excel无法打开文件'。如果我把report.xls作为名字,我可以打开excel,但是有些字节没有任何意义。
任何建议有什么不对?
没什么..不过同样的问题,同样的行为.. –
也许尝试在'axios.post设置'config parameter property'responseType:'blob',而不是在回调中转换它。 – barbsan
我已经完成了将响应类型放入发布请求。 'axios.post( 网址+ '报告', 查询, {头:{ “访问控制允许报头”: “*”, “X-XSRF-TOKEN”:这$ cookie.get ('XSRF-TOKEN') }, responseType:“arraybuffer”, } ).....' –