2. 准备工具类(EasyExcelUtil)com.alibaba easyexcel 3.0.5 org.apache.poi poi 4.1.2
public class EasyExcelUtil {
public static String write(String fileName, Class tClass, List list) {
String dirPath = System.getProperty("user.dir") + "/excel/" + tClass.getSimpleName() + "/";
File file = new File(dirPath);
//如果目录不存在,创建目录
if (!file.exists()) {
file.mkdirs();
}
String name = fileName + ".xlsx";
name = dirPath + name;
EasyExcel.write(name, tClass)
.sheet()
.doWrite(list);
return name;
}
public static ResponseEntity download(String path) throws IOException {
File file = new File(path);
byte[] data = Files.readAllBytes(file.toPath());
ByteArrayResource bar = new ByteArrayResource(data);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.length()).header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(path.substring(path.lastIndexOf("/") + 1), "UTF8").replace("+", "%20")).body(bar);
}
}
3. 后端准备
1.在对象类上加标注@ExcelIgnoreUnannotated
2.在需要导出的属性上加标注@ExcelProperty
3.写接口
@PostMapping("/excel/demo")
public ResponseEntity excelType(@RequestBody List list) throws IOException {
String path = EasyExcelUtil.write("表格名", Demo.class, list);
ResponseEntity download = EasyExcelUtil.download(path);
return download;
}
EasyExcelUtil.write(表格名字,对象类.class,列表)可以在后台创建表格,并返回表格所在地址的路劲。
EasyExcelUtil.download(path)可以将表格通过流传到前端。
- 输入指令npm i js-file-download -s下载js-file-download
- 打开main.js,进行三处修改
import jsFileDownload from 'js-file-download';
Vue.prototype.jsFileDownload = jsFileDownload;
if( res.data.status === 'OK'|| res.status==200){
return res;
}
- 写前端方法
handleExport() {
this.axios({
method: "post",
url: "http://localhost:8080/excel/demo",
data: 填写需要导出的集合,
responseType: "blob"//返还的数据类型
}).then(res => {
this.jsFileDownload(res.data, decodeURIComponent("表格.xlsx"));
})}
//decodeURIComponent()括号中自定义表格的名字。



