一、java
1、添加依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
2、封装方法
java
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ExcelUtils {
/**
* 导出excel
*/
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
File file = new File(tempPath);
BigExcelWriter writer= ExcelUtil.getBigWriter(file);
writer.write(list, true);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
ServletOutputStream out=response.getOutputStream();
// 终止后删除临时文件
file.deleteOnExit();
writer.flush(out, true);
//关闭输出Servlet流
IoUtil.close(out);
}
}
2、接口
java
@PostMapping("/exportList")
public void exportListData(@RequestBody List<Map<String,Object>> list,HttpServletResponse response){
try {
ExcelUtils.downloadExcel(list, response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
二、vue(代码块,仅参考)
1、前端API写法:
html
export function exportList(data) {
return request({
url: '/xxx/xxx/exportList/',
method: 'post',
responseType: "blob",
data: data
})
}
2、页面调用方法和导出文件
html
exportList(this.data).then(rsp => {
let blob = new Blob([rsp], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
let url = window.URL.createObjectURL(blob);
window.location.href = url;
this.$message({
showClose: true,
message: "文件下载成功",
type: "success",
});
});