Vue文件下载,文件导出

837 阅读2分钟

        很多人的项目中都有文件下载,文件导出为excel,json等格式的需求,最近我的项目中也有很多这种需求。现在给大家分享一下我是怎么做的:

目录

        1.html代码

        2.安装 js-file-download插件

        3.文件引用

        4.api文件代码

        5.js代码

        6.导出结果展示


        下面是项目效果图,右上角的导出,就是我们这次要实现的功能。由于都是真实的数据我在这儿就打码了。

         1.html代码

(本次项目用的element plus组件库)为按钮绑定

   <el-button
            type=""
            @click="exportIn"
            style="background: #5d78ff; color: #fff"
            >导出</el-button
          >

         2.安装 js-file-download插件

npm install js-file-download

        3.文件引用

import fileDownload from "js-file-download";

        4.api文件代码

注意:必须加上 responseType: 'blob' 这行代码,不然下载下来的文件会损坏

// 导出
export function exportSelectRoster(data) {
	return request({
		url: '/api/roster/exportSelectRoster',
		method: 'post',
		data,
		responseType: 'blob',
	})
}

        5.js代码

(注意:这里的fileDownload(res,"人员名册.xlsx") 这里是因为我这儿的需求是导出为Excel文件 所以这样写,如果你需要的是导出为其他文件,那你只需把后缀改成你需要的就行了,例如压缩包就.zip就行了)

// 导出
const exportIn = () => {
//检测是否表格勾选了数据
  if (deleteList.value.length == 0) {
    ElMessage.warning("请选择后导出");
    return;
  }
//提示用户是否导出
  ElMessageBox.confirm("你确定要导出此数据吗", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
//调导出接口 传递后端需要的数据
    exportSelectRoster({
      rosterId: deleteList.value,
    }).then((res) => {
//用fileDownload(后端返给的数据,文件名+后缀)
      console.log(res);
      fileDownload(res, "人员名册.xlsx");
      ElMessage.success("导出成功");
    });
  });
};

        6.导出结果展示

(然后我们就导出下载为Excel文件了)