下载Excel 显示下载状态

349 阅读1分钟

下载逻辑

使用方法: exportExcel(接口名) 如果发现错误,敬请指正。[狗头]

// 全局下载状态
let globalStatus = 'none' 
/**
 * 导出Excel
 * @param url 接口名
 * @description 查询条件拼接在url中 url?a=1&b=2
 */
 
const exportExcel = (url) => {
    // 点击提示状态
    if (globalStatus !== 'none') {
        // show({ msg : '正在导出!', title : '提示' });
        return
    }
    // 调用下载 xls
    downloadFile(url, 'POST', exportExcelCallback);
}

// 执行下载方法
const downloadFile = (url, method, cb) => {
    cb('waiting')
    
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 根据接口接收格式修改
    xhr.responseType = "blob";
    
    xhr.onprogress = () => cb('progress')
    
    xhr.onload = function () {
        cb('onload')
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 根据文件类型修改 type
            // xls => {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}
            // zip => { type: 'x-zip-compressed;charset=utf-8' }
            const blob = new Blob([xhr.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
            const csvUrl = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = csvUrl;
            link.download = 'file.xls'; // file.xls file.zip
            link.click();
            cb('downloaded')
        }
    }
    xhr.send();
}

const exportExcelCallback = (status) => {
    // 进行状态的判断 status
    console.log(status)
    globalStatus = status
    if (status === 'downloaded' || status === 'none') {
        console.log('未开始下载 或 已下载')
        globalStatus = 'none'
        // dom.removeClass('icon-download-animate') // 删除导出动画
    } else {
        console.log('正在下载')
        // dom.addClass('icon-download-animate') // 增加导出动画
    }
}

loading动画

iconfont下载一个圆圈 让它转

<div class="icons" style="background: url('/static/icon/loading.png') 0 0 no-repeat;width: 16px;height: 16px;"></div>
<style>
    .icons {animation: loading 1s infinite linear;}
    @keyframes loading {
        0% {transform: rotate(0deg)}
        100% {transform: rotate(360deg)}
    }
</style>