0
点赞
收藏
分享

微信扫一扫

Vue 将二进制文件转为excel


1、接口返回的是文件流

function download_excel (data) {
    const aLink = document.createElement('a')
    const blob = new Blob([res], { type: 'application/vnd.ms-excel,charset=utf-8' })
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', 'example' + '.xlsx')
    aLink.click()
}

2、接口返回的是base64

// 方法1
function download_excel (data) {
    const sliceSize = 512;
    const byteCharacters = atob(data);
    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    const file = new File(byteArrays, 'example.xls', {type: 'application/vnd.ms-excel,charset=utf-8'});
    const aLink = document.createElement('a')
    aLink.href = URL.createObjectURL(file)
    aLink.setAttribute('download', 'example' + '.xls')
    aLink.click()
}
// 方法2
unction download_excel (data) {
    const raw = atob(dat)
    const uInt8Array = new Uint8Array(raw.length)
    for (let i = 0; i < raw.length; i++) {
        uInt8Array[i] = raw.charCodeAt(i)
    }
    const aLink = document.createElement('a')
    const blob = new Blob([uInt8Array], { type: 'application/vnd.ms-excel,charset=utf-8' })
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', 'example' + '.xlsx')
    aLink.click()
}


举报

相关推荐

0 条评论