使用hutool工具进行导入导出excel表格
参考: https://blog.csdn.net/Java_LiShu/article/details/124233457
前台调用1:
window.open("/zhengxie/cppccproposal/exportExample?taPhone=13689878808")
前台调用2:
import request from '@/router/axios'
return request({
url: "/zhengxie/cppccproposal/exportExample",
method: "get",
responseType: "blob",
params: r //r 是对象,对应后台的po类
}).then(response => {
console.log(response)
const fileName = "心名字"
// 处理返回的文件流
const blob = response.data;
if (blob && blob.size === 0) {
this.$notify.error("内容为空,无法下载");
return;
}
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
window.setTimeout(function() {
window.URL.revokeObjectURL(blob);
document.body.removeChild(link);
}, 0);
});
后台代码:
@GetMapping("/exportExample")
@Inner(false)
//public R exportExample(Integer cs,String cs2){
public void exportExample(CppccProposal cppccProposal, HttpServletResponse response) throws IOException {
//查询所有用户
Map<String, Object> row1 = new LinkedHashMap<>();
row1.put("username", "张三");
row1.put("password", 23);
row1.put("nickname", 88.32);
row1.put("email", true);
Map<String, Object> row2 = new LinkedHashMap<>();
row2.put("username", "李四");
row2.put("password", 33);
row2.put("nickname", 59.50);
row2.put("email", false);
ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2);
ExcelWriter writer= ExcelUtil.getWriter(true);
//自定义标题别名
writer.addHeaderAlias("username","姓名");
writer.addHeaderAlias("password","年龄");
writer.addHeaderAlias("nickname","成绩");
writer.addHeaderAlias("email","是否合格");
//默认配置
writer.write(rows,true);
//设置content—type
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
//设置标题
String fileName= URLEncoder.encode("用户信息","UTF-8");
//Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
ServletOutputStream outputStream= response.getOutputStream();
//将Writer刷新到OutPut
writer.flush(outputStream,true);
outputStream.close();
}
择善人而交,择善书而读,择善言而听,择善行而从。