vue+ elementUI纯前端下载excel文件模板 React可直接使用同样方法下载静态资源文件
·
elementUI下载按钮:
<el-button type="warning" @click="downloadExcel">下载Excel模板</el-button>
vue methods中的方法:
downloadExcel() {
let a = document.createElement("a");
a.href = "./static/fileTemp.xlsx";
a.download = "文件模板.xlsx";
a.style.display = "none";
document.body.appendChild(a);
a.click();
a.remove();
},
或者通过 fetch 获取文件数据,然后使用 Blob 方式下载:
const downloadExcel = async () => {
const fileUrl = './static/fileTemp.xlsx';
const fileName = '模板文件.xlsx';
try {
const response = await fetch(fileUrl);
if (!response.ok) throw new Error('文件下载失败');
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
// 释放内存
setTimeout(() => window.URL.revokeObjectURL(url), 100);
} catch (error) {
console.error('下载失败:', error);
alert('文件下载失败,请检查网络或联系管理员');
}
}
在项目public目录下新建static文件夹,放入“fileTemp.xlsx”文件即可实现vue+ elementUI纯前端下载excel文件模板。
如果本地启动项目,下载提示:“无法从网站上提取文件”,将
a.href = "./static/fileTemp.xlsx";
修改为
a.href = "/static/fileTemp.xlsx";
即可成功下载模板。
React项目也可以直接使用downloadExcel方法下载。
更多推荐



所有评论(0)