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方法下载。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐