下载文件xlsx

184 阅读1分钟

1、点击事件 index.vue

    <el-link type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate"
            >下载模板</el-link>

2、处理方法 index.vue

    //导入请求方法及文件流处理方法
    import { exportTemplate } from "@/xxxxxxxx";
    import { downloadFile } from "@/utils/index";

    importTemplate() {
      exportTemplate().then(res => { // 请求接口 res为流对象
        downloadFile(res, "客户导入模板", "xlsx"); // e1:流对象 e2: 自定义文件名 e3:文件格式后缀
      });
    },

3、处理流对象的方法 utils/index.js


export function downloadFile(obj, name, suffix) {
  const fileName = parseTime(new Date()) + "-" + name + "." + suffix;
  if (window.navigator.msSaveBlob) {
    try {
      window.navigator.msSaveBlob(new Blob([obj]), fileName);
      //console.log("1111");
    } catch (e) {
      console.log(e);
    }
  } else {
    const link = document.createElement("a");
    let blob = new Blob([obj], {
      type: "application/vnd.ms-excel"
    });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}