zoukankan      html  css  js  c++  java
  • vue~使用axios实现excel文件下载的实现

    前端VUE页面上的导出或者下载功能,一般是调用后端的一个接口,由接口生成excel,word这些文件的流信息,返回给vue,然后由vue去构建下载的动作,这边整理了一下,封装了一下,方便以后复用。

    封装一个download文件

    使用年月日时分秒毫秒做为文件的名称,下载为excel文件

    /**
     * 下载文件
     */
    export const downloadFile = (url,ext, params) => {
        let accessToken = getStore('accessToken');
        return axios({
            method: 'get',
            url: `${base}${url}`,
            params: params,
            headers: {
                'accessToken': accessToken
            },
            responseType: 'blob', //二进制流
        }).then(res => {
            // 处理返回的文件流
            const content = res;
            const blob = new Blob([content], { type: 'application/vnd.ms-excel;charset=utf-8' });
            var date =
                new Date().getFullYear() +
                "" +
                (new Date().getMonth() + 1) +
                "" +
                new Date().getDate() +
                "" +
                new Date().getHours() +
                "" +
                new Date().getMinutes() +
                "" +
                new Date().getSeconds() +
                "" +
                new Date().getMilliseconds();
            const fileName = date + "." + ext;
            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);
            }
        });
    };
    

    为具体功能封装一个组件,方便在前台调用

    
    // 评价导出
    export const getRecordExport= (params) => {
        return downloadFile('/record/export',"xlsx", params)
    }
    

    vue页面上调用它,实现导出

    <script>
    import {
      getReportExport
    } from "@/api/index";
    import util from "@/libs/util.js";
    
    export default {
      name: "task-manage",
     data() {},
     methods: {
       exportExcel() {
          getReportExport(this.searchForm).then(res=>{});
        }
     }
    }
    

    截图
    截图

  • 相关阅读:
    通用客户端脚本
    刷一次变一次图的ASP代码
    ASP公共翻页代码
    Web中模态对话框加载后根据加载内容动态改变其大小并使其居中
    创建一个ASP通用分页类
    各大门户网站FLASH广告完全揭密
    插入记录后,获取记录的ID
    ASP实用函数库
    Sametime 8.5.1系统环境要求
    推荐:IBM Lotus Domino 8.5 服务器管理入门手册(适用初学者)
  • 原文地址:https://www.cnblogs.com/lori/p/13322246.html
Copyright © 2011-2022 走看看