一、后台部分
1、导入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.2.1</version> </dependency>
2、创建Excel的实体模型
@ContentRowHeight(120)public class EmployeeResp {/** * 主键 */ @ExcelProperty("主键") private Long id; /** * 登录账户 */ @ExcelProperty("登录账户") private String loginName; /** * 性别(0 女 1 男) */ @ExcelProperty("性别") private String gender; /** * 状态(1停用,0正常) */ @ExcelProperty("状态") private String status; /** * 头像 */ //图片导出是url的地址字符串解决方法 //1.使用查看文档StringImageConverter编写这种类,ImageCovert(下面有代码) @ColumnWidth(25) @ExcelProperty(value = "头像",converter = ImageConvert.class) private String avatar; //2是使用内置的url转换的类URL对地址进行转换再输出 // @ExcelIgnore // private String avatar; // // @JsonIgnore // @ExcelProperty(value="头像") // private URL url; // // @JsonIgnore // public URL getUrl() throws MalformedURLException { // return new URL(this.avatar); // } }
public class ImageConvert implements Converter<String> { @Override public Class<?> supportJavaTypeKey() { return String.class; } /** * 把转换后的结果写入到excel单元格中 * @param value * @param contentProperty * @param globalConfiguration * @return * @throws IOException */ @Override public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { //value =https://waimai-1300180953.cos.ap-chongqing.myqcloud.com/images/d315ccf5-c0f9-4169-8056-33e64dcbd0b9.png //1、创建一个http请求对象 (spring 框架封装的) RestTemplate restTemplate=new RestTemplate(); try { byte[] forObject = restTemplate.getForObject(value, byte[].class); return new WriteCellData<>( forObject ); }catch (Exception e){ return new WriteCellData<>("图片下载失败"); } //return new WriteCellData(FileUtils.readFileToByteArray(new File(value))); } }
3、写请求(查看文档写Excel | Easy Excel (alibaba.com))
public void download(EmployeeSearchReq req,HttpServletResponse response) throws IOException { // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("表名", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); List<EmployeeResp> employeeRespList = this.employeeService.find(req); EasyExcel.write(response.getOutputStream(), EmployeeResp.class).sheet("sheet工作簿的名").doWrite(employeeRespList); }
二、前端
1、项目内添加依赖file-saver
npm install file-saver --save
2、在编写request.js(前端拦截器),用的element2
import { MessageBox, Message, Loading} from 'element-ui'
import {saveAs} from 'file-saver'instance.interceptors.response.use(
(response) => {
//判断是不是 blob下载,如果是blob不要再往下面走
if(response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer'){
return response.data
}
。。。。。这些的拦截器的东西
}let downloadLoadingInstance;
// 通用下载方法
export function download(url, data, filename,config) {
downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", background: "rgba(0, 0, 0, 0.7)", })
//url就是请求路径
return Loading.post(url, data, {
responseType: 'blob',
...config
}).then(async (resp) => {
//判断返回结果是不是一个二进制文件
const isBlob = await blobValidate(resp);
if (isBlob) {
const blob = new Blob([resp])
saveAs(blob, filename)
} else {
const resText = await resp.text();
const rspObj = JSON.parse(resText);
const errMsg = rspObj.msg
ElMessage.error(errMsg);
}
downloadLoadingInstance.close();
}).catch((r) => {
console.log(r)
ElMessage.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close();
})
}// 验证是否为blob格式
async function blobValidate(data) {
try {
const text = await data.text();
//数据尝试转换成json对象
JSON.parse(text);
return false;
} catch (error) {
return true;
}
}
3.调用方法传参数就可以了(这边将download注册成全局方法)
在main.js中加
import { download } from '@/utils/request'
// 全局配置
Vue.prototype.download = download
具体在哪里调用就可以了