后端
导入pom依赖
<dependency>x<groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.2.0</version>
</dependency>
Entity实体类
这里以User为例,可按照自己实际情况进行修改
@Excel:著名为导出字段 @ExcelIgnore:忽略导出字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User extends Account implements Serializable {private static final long serialVersionUID = 1L;/** ID */@Excel(name = "ID",orderNum = "0",width = 15)private Integer id;/** 用户名 */@Excel(name = "用户名",orderNum = "1",width = 15)private String username;/** 密码 */@ExcelIgnoreprivate String password;/** 姓名 */@Excel(name = "姓名",orderNum = "2",width = 15)private String name;/** 电话 */@Excel(name = "电话",orderNum = "3",width = 15)private String phone;/** 邮箱 */@Excel(name = "邮箱",orderNum = "4",width = 15)private String email;/** 头像 */@ExcelIgnoreprivate String avatar;/** 角色标识 */@ExcelIgnoreprivate String role;/** 验证码*/@ExcelIgnoreprivate String kaptcha;
}
自定义Service
public List<User> exportUsers(){List<User> list = userMapper.selectExcel();return list;}
自定义控制器
@GetMapping(value = "/export")public void exportUsers(HttpServletResponse response) throws IOException {try {// 设置下载弹窗的文件名和格式(文件名要包括名字和文件格式)List<User> allList = userService.exportUsers();// 获取数据//导出操作ExcelUtil.exportExcel(allList,"用户信息表","用户信息表",User.class,"用户信息表.xls",response);} catch (Exception e) {e.printStackTrace();}}
前端
在自定义拦截器中添加判断
request.interceptors.response.use(response => {let res = response.data;if(res.type === "application/vnd.ms-excel" && response.status === 200){// 说明是excelreturn response;}// 兼容服务端返回的字符串数据if (typeof res === 'string') {res = res ? JSON.parse(res) : res}if (res.code === '401') {router.push('/login')}return res;},error => {console.error('response error: ' + error) // for debugreturn Promise.reject(error)}
)
添加按钮点击事件
<el-button type="success" plain @click="handlerExport">导出</el-button>
自定义组件用于导出
import request from "@/utils/request";
export function exportMemberList(){return request({url: '/user/export',method: 'get',responseType: 'blob',header: {headers: {'Content-Type': 'application/x-download'}},})
}
定义函数
handlerExport(){exportMemberList().then((response) => {this.downloadFile(response, "员工信息表.xls");this.$message({showClose: true,message: "导出成功",type: "success",});})},downloadFile(res, fileName) {const content = res.data;const blob = new Blob([content]);if ("download" in document.createElement("a")) {// 非IE下载const elink = document.createElement("a");elink.download = fileName;elink.style.display = "none";elink.href = URL.createObjectURL(blob);document.body.appendChild(elink);elink.click();URL.revokeObjectURL(elink.href); // 释放URL 对象document.body.removeChild(elink);} else {// IE10+下载navigator.msSaveBlob(blob, fileName);}},