导出页面内容为表格文件

vue2导出表格

1.下载保存文件插件

npm i file-saver --asve

2.在想导出页面引入

import { saveAs } from "file-saver"

3.配置接口参数

// 导出文件接口

export const CustomerExportApi = (params, configs) => instance.post("/prod-api/customer/export", params, configs)

4.使用接口导出文件

事件

触发 

// 导出
    async exec() {
      // 调用导出接口
      const res = await CustomerExportApi({
        pageNum: 1,
        pageSize: 10
      }, {
        // 配置响应头,把二进制转换为表格
        headers: {
          "Content-Type": "application/X-www-from-urlencoded"
        },
        responseType: "blob"
      })
      if (!res) return
      console.log(res);
      // 导出文件和设置文件名称加时间为文件名避免重复文件名
      saveAs(
        new Blob([res]), `客户档案_${new Date().getTime()}.xlsx`
      )
    },

vue3导出表格

下载

npm install xlsx

 引入

import * as XLSX from 'xlsx'; // Vue3 版本 

 事件

<el-button class="getExport" @click="detail_Export" type="primary">导出</el-button> 

 触发

// 导出表格
async function detail_Export() {
  // 请求接口数据
  const res: any = await Emolument_get_salary({
    staff_id: staff_id.value || "",
    month_id: time_id.value || "",
    branch_id: branch_id.value || ""
  })
  if (res.code === 1) {
    // 定义表格头部标题
    let head: any = {
      branch_id: '部门',
      staff_name: "姓名",
      order_number: "订单编号",
      deal_total_price: "成交金额",
      jing_profit: "净利润",
      return_money: "单笔回款金额",
      createtime: "回款时间",
      actual_return_money: "实际回款金额",
      return_money_total: "实际总回款",
      get_profit: "单笔到账利润",
      percent_name: "提成比例",
      get_money: "提成金额",
    }
    // 遍历数据
    let list: any = res.data.detail.map((item: { [x: string]: any; }) => {
      const obj: any = {}
      for (const k in item) {
        if (head[k]) {
          if (head[k] == "部门") {
            obj[head[k]] = item[k] == '1' ? "第一个部门" : "第二个部门"
          } else {
            obj[head[k]] = item[k]
          }
        }
      }
      return obj
    })
    // 创建工作表
    const data = XLSX.utils.json_to_sheet(list)
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    // 将工作表放入工作簿中
    XLSX.utils.book_append_sheet(wb, data, '薪酬统计提成明细列表')
    // 生成文件并下载
    XLSX.writeFile(wb, '薪酬统计提成明细列表.xlsx')
  } else {
    //导出失败提示
    ElMessage.error(res.msg)
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_70563937/article/details/127801137