vue 导出excel模块

本文介绍了在Vue应用中通过`download`属性、后端提供文件URL以及js-file-download插件实现文件下载的三种方法,重点讲解了Blob对象在Excel导出中的运用,并对比了它们的优缺点及适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【方法1—通过 a 标签 download 属性结合 blob 构造函数下载】
在这里插入图片描述

reportTotal.vue

<template>
    <div class="reportTotal">
        <el-button type="primary" @click="handleExport">导出</el-button>
    </div>
</template>
<script>
import reportTotal from '@/api/reportTotal'
export default {
    data(){
        return {
            dateStr: ''
        }
    },
    methods: {
        handleExport(){
            let temp = {dateStr: this.dateStr}//2021-05
            reportTotal.exportExcel(temp).then(res =>{
                const blob = new Blob([res.data],{type: 'application/vnd.ms-excel;charset=utf-8'})//构造一个blob对象来处理数据并设置文件类型
                const href = window.URL.createobjectURL(blob)//创建新的URL表示指定的blob对象
                const element = document.createElement('a')//创建a标签
                element.href = href//指定下载链接
                element.download = '数据治理报表.xls'//下载文件名
                document.body.appendchild(element)//将a标签插入页面中
                element.click()//触发下载
                document.body.removeChild(element)//清除a标签
                window.URL.revokeObjectURL(href)//释放URL对象
            })
        }
    }
}
</script>

reportTotal.js

import request from '@/request'
export default {
	exportExcel(data){
		return request({
			url: '/exposure/export/exporttotalList',//服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'
			method: 'get',
			response: 'blob',
			params: data
		})
	}
}

注:请求后台接口时要在请求头上加{responseType: ‘blob’};download 设置文件名时,可以直接设置扩展名,如果没有设置浏览器将自动检测正确的文件扩展名并添加到文件。

【方法2—通过 url 下载】
即后端提供文件的地址,直接使用浏览器去下载

通过 window.location.href = 文件路径下载
window.location.href = ${location.origin}/exposure/export/exporttotalList

通过 window.open(url, ‘_blank’)
window.open(${location.origin}/exposure/export/exporttotalList)

这两种使用方法的不同:

window.location:当前页跳转,也就是重新定位当前页;只能在网站中打开本网站的网页。

window.open:在新窗口中打开链接;可以在网站上打开另外一个网站的地址。

【方法3—通过 js-file-download 插件下载】
安装:npm install js-file-download --S
使用:

import fileDownload from 'js-file-download'

axios.get(`/exposure/export/exporttotalList`, {
        responseType: 'blob' //返回的数据类型
    })
    .then(res => {
        fileDownload(res.data, this.fileName)
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值