栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot项目使用js-file-download与easyexcel在基于vue的页面上下载excel文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot项目使用js-file-download与easyexcel在基于vue的页面上下载excel文件

1. 导入依赖
    
    com.alibaba    
    easyexcel    
    3.0.5

    
    org.apache.poi    
    poi    
    4.1.2

2. 准备工具类(EasyExcelUtil)
public class EasyExcelUtil {
    
    public static  String write(String fileName, Class tClass, List list) {
        String dirPath = System.getProperty("user.dir") + "/excel/" + tClass.getSimpleName() + "/";
        File file = new File(dirPath);
        //如果目录不存在,创建目录
        if (!file.exists()) {
            file.mkdirs();
        }
        String name = fileName + ".xlsx";
        name = dirPath + name;
        EasyExcel.write(name, tClass)
                .sheet()
                .doWrite(list);
        return name;
    }

    
    public static ResponseEntity download(String path) throws IOException {
        File file = new File(path);
        byte[] data = Files.readAllBytes(file.toPath());
        ByteArrayResource bar = new ByteArrayResource(data);
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.length()).header("Content-Disposition", "attachment; filename=" + URLEncoder.encode(path.substring(path.lastIndexOf("/") + 1), "UTF8").replace("+", "%20")).body(bar);
    }
}
3. 后端准备

1.在对象类上加标注@ExcelIgnoreUnannotated

2.在需要导出的属性上加标注@ExcelProperty

3.写接口

@PostMapping("/excel/demo")
public ResponseEntity excelType(@RequestBody List list) throws IOException {    
String path = EasyExcelUtil.write("表格名", Demo.class, list);    
ResponseEntity download = EasyExcelUtil.download(path);    
return download;
}

EasyExcelUtil.write(表格名字,对象类.class,列表)可以在后台创建表格,并返回表格所在地址的路劲。
EasyExcelUtil.download(path)可以将表格通过流传到前端。

4. 前端准备
  1. 输入指令npm i js-file-download -s下载js-file-download
  2. 打开main.js,进行三处修改
import jsFileDownload from 'js-file-download';

Vue.prototype.jsFileDownload = jsFileDownload;

if( res.data.status === 'OK'|| res.status==200){
  return res;
}
  1. 写前端方法
handleExport() {    
    this.axios({        
    method: "post",        
    url: "http://localhost:8080/excel/demo",        
    data: 填写需要导出的集合,        
    responseType: "blob"//返还的数据类型    
    }).then(res => {        
        this.jsFileDownload(res.data, decodeURIComponent("表格.xlsx"));    
})}

//decodeURIComponent()括号中自定义表格的名字。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1034993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号