前端代码:
<el-button class="filter-item" type="success" size="mini" plain icon="el-icon-download"
@click="exportExcel">
导出
</el-button>
exportExcel方法:
exportExcel() {
download(this.table.searchForm).then(res => {
const blob = new Blob([res.data])
const filename = res.headers['content-disposition']
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = decodeURIComponent(filename.split('filename=')[1])
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
}).catch(function (error) {
console.log(error);
})
},
实体类:
@Data
public class LogExcel {
@Excel(name = "登录名称" ,width = 20,needMerge = true)
private String username;
@Excel(name = "模块名称" ,width = 20,needMerge = true)
private String module;
@Excel(name = "操作" ,width = 20,needMerge = true)
private String handle;
@Excel(name = "操作时间" ,width = 20,needMerge = true)
private String createDate;
@Excel(name = "请求地址" ,width = 20,needMerge = true)
private String requestUri;
@Excel(name = "请求方法" ,width = 20,needMerge = true)
private String requestMethod;
@Excel(name = "请求参数" ,width = 20,needMerge = true)
private String requestParams;
@Excel(name = "响应结果" ,width = 20,needMerge = true)
private String responseResult;
@Excel(name = "响应时间" ,width = 20,needMerge = true)
private Long responseTime;
private String fromTime;
private String toTime;
}
后端impl代码:
@Override
public Workbook excelOut(LogExcel logExcel) {
List<LogExcel> log = logMapper.logExcelOut(logExcel);
ExportParams exportParams = new ExportParams();
exportParams.setSheetName("日志");
Map<String, Object> map = new HashMap<>();
// title的参数为ExportParams类型,目前仅仅在ExportParams中设置了sheetName
map.put("title", exportParams);
// 模版导出对应得实体类型,即包含了List的对象
map.put("entity", LogExcel.class);
// sheet中要填充得数据
map.put("data", log);
List<Map<String, Object>> sheetsList = new ArrayList<>();
sheetsList.add(map);
return ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
}
controller:
@PostMapping("/download")
@ResponseBody
@PreAuthorize("hasPermission('/core/log/download','b:log:open')")
public void exportDaIlyTable( @RequestBody LogExcel logExcel, HttpServletResponse response) throws IOException {
Workbook workbook = logService.excelOut(logExcel);
String fileName = URLEncoder.encode("日志.xlsx" , "UTF-8");
//设置响应头,控制浏览器下载该文件
response.reset();
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.setHeader(Constants.HEADER_DOWNLOAD, "true");
response.setContentType("application/octet-stream");
//创建输出流
OutputStream out = response.getOutputStream();
workbook.write(out);
//关闭输出流
out.close();
}
在发请求的时候需要加上
responseType: 'blob'
导出: