axios文件下载!!!!
前端
download(){
debugger;
this.loading = true;
axios.post('http://localhost:8081/brand_case/dao.do?method=export',this.queryParams,{
responseType: 'blob'
}).then( res=>{
console.log('res', res)
// var data = res.data.data;
// 截取文件名,这里是后端返回了文件名+后缀,如果没有可以自己拼接
// 切割出文件名
const fileNameEncode = res.headers['content-disposition'].split('filename=')[1]
/// 解码
const fileName = decodeURIComponent(fileNameEncode)
console.log('fileName', fileName)
// 设置type类型
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; application/octet-stream'
})
const fileUrl = window.URL.createObjectURL(blob)
let a = document.createElement("a");
a.href = fileUrl
console.log('url', fileUrl)
a.setAttribute('download', fileName)
a.style.display = 'none'
a.click()
a.remove()
this.loading = false;
}
)
}
}
后端---模板
package com.itheima.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@HeadRowHeight(value = 30)
@ContentRowHeight(value = 25)
@ColumnWidth(value = 30)
public class UserExcel {
@ExcelProperty(value = "用户编号")
private Integer userId;
@ExcelProperty(value = "姓名")
private String username;
@ExcelProperty(value = "性别")
private String gender;
@ExcelProperty(value = "工资")
private Double salary;
@ExcelProperty(value = "入职时间")
private Date hireDate;
}
controller
// 设置响应头
resp.setContentType("application/vnd.ms-excel");
resp.setCharacterEncoding("utf-8");
// 设置防止中文名乱码
String filename = URLEncoder.encode("员工信息", "utf-8");
// 文件下载方式(附件下载还是在当前浏览器打开)
resp.setHeader("Content-disposition", "attachment;filename=" +
filename + ".xlsx");
// 构建写入到excel文件的数据
List<UserExcel> userExcels = new ArrayList<>();
UserExcel userExce1 = new UserExcel(1001, "张三", "男", 1333.33,
new Date());
UserExcel userExce2 = new UserExcel(1002, "李四", "男", 1356.83,
new Date());
UserExcel userExce3 = new UserExcel(1003, "王五", "男", 1883.66,
new Date());
UserExcel userExce4 = new UserExcel(1004, "赵六", "男", 1393.39,
new Date());
userExcels.add(userExce1);
userExcels.add(userExce2);
userExcels.add(userExce3);
userExcels.add(userExce4);
// 写入数据到excel
EasyExcel.write(resp.getOutputStream(), SysOperLog.class)
.sheet("用户信息")
.doWrite(logQuery);