Vue結合后台實現導出功能
轉載:https://blog.csdn.net/liujun03/article/details/84378942
/**
* 批量導出用戶
* @param condition
* @param response
*/
@PostMapping("/exportUser")
public void exportUser(@RequestBody UserQueryCondition condition,HttpServletResponse response){
XSSFWorkbook book = new XSSFWorkbook();
try {
List<UserParam> list = indexService.exportUser(condition);
if (list != null && list.size() > 0) {
XSSFSheet sheet = book.createSheet("mySheent");
String[] vals = {"用戶ID", "郵箱賬號","昵稱","年齡","性別","狀態", "注冊時間"};
createExcel(sheet, 0, vals);
for (int i = 0; i < list.size(); i++) {
UserParam entity = list.get(i);
String[] vals2 = new String[]{String.valueOf(entity.getId()), entity.getEmail(), entity.getName(), String.valueOf(entity.getAge()),
entity.getSex() == 0 ? "女":"男",entity.getRemoved() == 0 ? "啟用":"禁用",entity.getRegisterDate()};
createExcel(sheet, i + 1, vals2);
}
book.write(generateResponseExcel("用戶列表",response));
}
book.close();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* @param excelName
* 要生成的文件名字
* @return
* @throws IOException
*/
private ServletOutputStream generateResponseExcel(String excelName, HttpServletResponse response) throws IOException {
excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
return response.getOutputStream();
}
對於第一個函數exportUser
來說,主要是根據傳回來的條件查詢數據庫並生成相應的Excel表格,之后book.write(generateResponseExcel(“用戶列表”,response)); 這行代碼調用第二個函數generateResponseExcel
來生成流文件以及處理返回的Response。
這里需要注意的地方就兩個:
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
第一行application/vnd.ms-excel說明將結果導出為Excel
第二行說明提供那個打開/保存對話框,將文件作為附件下載
上面就是后台的全部代碼了,接下來看一下前端的代碼:
axios({
method: 'post',
url: 'http://localhost:19090/exportUser',
data: {
email: this.email,
userIdArray: this.userIdArray,
startRegisterDate: this.registerStartTime,
endRegisterDate: this.registerEndTime
},
responseType: 'blob'
}).then((res) => {
console.log(res)
const link = document.createElement('a')
let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
link.style.display = 'none'
link.href = URL.createObjectURL(blob);
let num = ''
for(let i=0;i < 10;i++){
num += Math.ceil(Math.random() * 10)
}
link.setAttribute('download', '用戶_' + num + '.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}).catch(error => {
this.$Notice.error({
title: '錯誤',
desc: '網絡連接錯誤'
})
console.log(error)
})
這里為了方便做記錄,我是直接在頁面中使用axios發送了個post請求。
仔細看axios請求加了個responseType: 'blob'
配置,這是很重要的