Springboot + Vue + EasyExcel 【导出和导入】

Spring boot +Vue + EasyExcel [导出案例]

EasyExcel官方文档地址

EasyExcel 是什么?

EasyExcel 是一个基于java的简单,省内存的读写Excel的开源项目。在尽可能节省内存的情况下支持读写百万M的Excel.

1 导入依赖

   
 	    <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>easyexcelartifactId>
            <version>3.1.0version>
        dependency>

1 Controller

    @PostMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        String token =jsonObject.getString("token");
        int id= JwtUtil.getIdToken(token);
        List<Order> orderList=indexService.showOrder(id);
        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");
        EasyExcel.write(response.getOutputStream(), Order.class).sheet("模板").doWrite(orderList);
    }

2 Vue页面

 this.axios.post("http://localhost:8181/demo/exportExcel", {token: token},{responseType:"blob"}).then(response => {
          let blob = new Blob([response.data], { type: 'application/vnd.ms-				excel;charset=utf-8' })
          let downloadElement = document.createElement('a');
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = '订单表.xlsx';     //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click();                     //点击下载
          document.body.removeChild(downloadElement);  //下载完成移除元素
          window.URL.revokeObjectURL(href);            //释放掉blob对象
        })

你可能感兴趣的:(vue.js,spring,boot,java)