后台代码,这是基础方法,还要根据使用调用
public static void exportExcel(HttpServletResponse response, String sheetName, String fileName, String[] header, List<String[]> content)
throws IOException {
// 清空response
response.reset();
// 设置response的Header
response.setHeader("Content-disposition",
"attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xlsx");
response.setContentType("application/vnd.ms-excel;charset=gb2312");
Sheet sheet = new Sheet(1, 0);
sheet.setSheetName(sheetName);
// 设置自适应宽度
sheet.setAutoWidth(Boolean.TRUE);
// 设置表头
List<List<String>> list = new ArrayList<>();
for (int i = 0; i < header.length; i++) {
list.add(Collections.singletonList(header[i]));
}
sheet.setHead(list);
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new BufferedOutputStream(response.getOutputStream());
writer = EasyExcelFactory.getWriter(outputStream);
List<List<Object>> data = new ArrayList<List<Object>>();
for (int i = 0; i < content.size(); i++) {
List<Object> item = new ArrayList<Object>();
for (int j = 0; j < content.get(i).length; j++) {
item.add(content.get(i)[j]);
}
data.add(item);
}
writer.write1(data, sheet);
outputStream.flush();
log.info("excel文件导出成功!");
} catch (Exception e) {
log.error("excel文件导出失败, 失败原因:{}", e);
} finally {
try {
if (writer != null) {
writer.finish();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件导出失败, 失败原因:{}", e);
}
}
}
前端请求:
<button type="primary" icon="ios-cloud-download" @click="download_file"
style=" color: rgb(255, 255, 255); background-color: rgb(45, 140, 240);border: 1px solid transparent; display: inline-block; margin-bottom: 0px; font-weight: 400; text-align: center; vertical-align: middle; touch-action: manipulation; cursor: pointer; background-image: none; white-space: nowrap; line-height: 1.5; user-select: none; height: 32px; line-height: 32px; padding: 0px 15px; font-size: 14px;border-radius: 4px;"
>导出数据</button>
download_file(){
const url = this.exportUrl+"?orderCode="+this.orderCode+"&productName="+this.productName+"&state"+this.state+"&productCode="+this.productCode+"&mobile="+this.mobile+"&commitTime="+this.commitTime+"&size=10000&page=1";
const token = store.getters.access_token
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer ' + token);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
var blob = e.currentTarget.response;
var filename = `productOrderList.xls`;//如123.xls
var a = document.createElement('a');
var url = URL.createObjectURL(blob);
a.href = url;
a.download=filename;
a.click();
window.URL.revokeObjectURL(url);
}
};
xhr.send();
},