前端程式碼
store 中的js檔案
import {excelExportTemplate
} from '@/api/xxxxx'
async excelExportTemplate ({commit}, fieldConfig) {
var res =await new Promise((resolve, reject) => {
excelExportTemplate(fieldConfig).then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
return res
},
api總的方法
import request from '@/utils/request'
const prefix = 'xxxxxx/'
export function excelExportTemplate (params) {
return request.post(prefix + 'excelExportTemplate',params, {
responseType: 'blob',
});//請求時,資料格式為blob
}
request由於是封裝的方法,增加blob格式方法
const res = response.data
if (response.data instanceof Blob&&response.status=="200"){
return res
}
vue中的方法
excelExportTemplateBtn: function () {
var querystring = require('querystring')
var param = {}
this.excelExportTemplate(querystring.stringify(param))
.then(resp => {
this.downloadExcel(resp,'欄位對映配置模板.xlsx')
this.$message({
type: 'success',
message:
'下載成功!'
});
})
},
downloadExcel (blobPart, filename) {
const blob = new Blob([blobPart], { type: 'application/vnd.ms-excel' })
// 建立一個超連結,將檔案流賦進去,然後實現這個超連結的單擊事件
const elink = document.createElement('a')
elink.download = decodeURIComponent(filename)
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 釋放URL 物件
document.body.removeChild(elink)
},
後端程式碼
@RequestMapping("excelExportTemplate")
public void excelExportTemplate( HttpServletResponse response) throws IOException {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 這裡URLEncoder.encode可以防止中文亂碼
String fileName = URLEncoder.encode("欄位對映配置模板", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
List<EntityVo> list = new ArrayList<EntityVo>();
// 這裡需要設定不關閉流
EasyExcel.write(response.getOutputStream(), EntityVo.class)
.head(EntityVo.class)
.registerWriteHandler(new DefaultStyle())
.registerWriteHandler(new CustomCellWriteWeightConfig())
.registerWriteHandler(new CustomCellWriteHeightConfig())
.autoCloseStream(Boolean.FALSE)
.sheet("sheet1")
.doWrite(list);
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = MapUtils.newHashMap();
map.put("status", "failure");
map.put("message", "匯出失敗" + e.getMessage());
response.getWriter().println(map);
}
}
實體類
@Data
public class EntityVo{
@ExcelProperty(value = "姓名", index = 0)
private String A1;
@ExcelProperty(value = "性別", index = 1)
private String A2;
@ExcelProperty(value = "年齡", index = 2)
private String A3;
@ExcelProperty(value = "愛好", index = 3)
private String A4;
@ExcelProperty(value = "顏色", index = 4)
private String A5;
@ExcelProperty(value = "介紹", index = 5)
private String A6;
}