导出easyExcel(前端vue2/后端springboot)

avatar
作者
猴君
阅读量:0

本来我是不想写这篇博文的,随着我技术的上升,已经很少有东西恶心我了,百度什么都能出来,但是百度出来的都是不能直接用的,所以我手写出来供我下次使用

后端

maven如下

<dependency> 	<groupId>com.alibaba</groupId> 	<artifactId>easyexcel</artifactId> 	<version>2.2.8</version> </dependency> 

实体类

 @Data @TableName("sys_logininfor") @ExcelIgnoreUnannotated public class SysLogininfor implements Serializable {     private static final long serialVersionUID = 1L;      /**      * ID      */     @ExcelProperty(value = "序号")     @TableId(value = "info_id", type= IdType.AUTO)     private Long infoId;       /**      * 登录状态 0成功 1失败      */     @ExcelProperty(value = "登录状态", converter = ExcelDictConvert.class)     @ExcelDictFormat(dictType = "sys_common_status")     private String status;      /**      * 登录IP地址      */     @ExcelIgnore     private String ipaddr;        /**      * 提示消息      */     @ExcelProperty(value = "提示消息")     private String msg;       /**      * 请求参数      */     @TableField(exist = false)     private Map<String, Object> params = new HashMap<>();  }  

util 工具类

//导出接口     public static <T> void export(HttpServletResponse response, Class<T> clazz, List<T> data, String fileName, String sheetName){         response.setContentType("application/vnd.ms-excel");         response.setCharacterEncoding("utf-8");         try{            fileName= new String((fileName + ExcelTypeEnum.XLSX.getValue()).getBytes(), StandardCharsets.ISO_8859_1);             response.setHeader("Content-Disposition", "attachment; filename="+fileName);             EasyExcelFactory.write(response.getOutputStream()).head(clazz).registerWriteHandler(new ExcelWidthStyleStrategy())                 .excelType(ExcelTypeEnum.XLSX)                 .sheet(sheetName).doWrite(data);         }catch(IOException e){             log.error("export excel error:",e);         }     }  

controller 接口

    @PostMapping("/export")     void export(JsonObject param,HttpServletResponse response){         List<SysLogininfor> list = new ArrayList<>();         String dateFormat = new DateTime().toString("yyyyMMddHHmmss");         String fileName =dateFormat +"统计";         export(response, SysLogininfor.class,list,fileName,"sheet1");     } 

前端:

js引入接口

export function export(data) { 	return request({ 		url: "/export", 		method: post, 		data: data, 		responseType:'arraybuffer' , 	}) } 

vue调用

  this.loading=true export({   params: {   } }).then(response => {   // 请求成功返回后,获取到Excel文件的二进制数据   const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });   // 创建下载链接   const downloadUrl = URL.createObjectURL(blob);   // 创建一个隐藏的a标签,设置下载链接和文件名,模拟点击下载   const link = document.createElement('a');   link.style.display = 'none';   link.href = downloadUrl;   link.download = '统计.xlsx';   document.body.appendChild(link);   link.click();   document.body.removeChild(link);   this.loading=false }).catch(error => {   // 请求失败处理   console.error(error); }); 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!