vue2动态渲染el-table + 前端导出excel

本文描述了一个前端项目中,如何使用Vue.js和ElementUI实现动态表单的渲染,包括选择日期、统计类型和服务站,以及如何通过file-saver和xlsx库导出表格数据。内容涉及表格数据的处理和前端与后端数据的交互。

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

<template>
  <div class="contact">
    <div class="input-box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="所属日期">
          <el-date-picker v-model="queryParams.planDate" type="month" placeholder="所属日期" format="yyyyMM"
            value-format="yyyyMM">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="统计类型">
          <el-select v-model="template_dataType" placeholder="请选择统计类型">
            <el-option :value="0" label="市局">市局</el-option>
            <el-option :value="1" label="县局">县局</el-option>
            <el-option :value="2" label="服务站">服务站</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务站" v-if="queryParams.dateType == 2">
          <el-select v-model="queryParams.deptId" placeholder="请选择服务站">
            <el-option v-for="(item, index) in dept_list" :key="index" :value="item.deptId" :label="item.deptName" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlerSearch">查询</el-button>
          <!-- <el-button @click="handlerResert">重置</el-button> -->
          <el-button @click="handlerExportData">导出</el-button>
          <!-- <el-button @click="add_dialog_show = true">新增</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <div class="content-box">
      <el-table :data="init_list" max-height="700" id="out-table">
        <el-table-column label="一级目录" prop="firDirectory" align="center" width="120" fixed="left" />
        <el-table-column label="二级目录" prop="secDirectory" align="center" width="150" fixed="left" />
        <el-table-column label="三级目录" prop="thirdDirectory" align="center" width="200" fixed="left" />
        <el-table-column v-for="(item, index) in header_list" :key="index" :label="item" align="center">
          <template slot-scope="scope">
            <div v-for="(itm, idx) in scope.row.valueList" :key="idx">
              {{ itm[item] || 0 }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
        @pagination="handlerInitList" /> -->
    </div>

  </div>
</template>

<script>
import { getStatisticsQueryList, getStatisticsQueryListHeader, getStatisticDept } from "@/api/grassrootsServices/statisticMessage/index"
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      queryParams: {
        planDate: '', //所属日期(yyyymm)
        dateType: '0', //统计类型(0市局1县局2服务站)
        deptId: null //当统计服务站时,需要传递营销部Id
      },
      template_dataType: '市局',

      total: 1,
      init_list: [],
      header_list: [],
      dept_list: []
    };
  },
  watch: {
    template_dataType(newValue) {
      this.queryParams.dateType = newValue
      if (newValue != 2) {
        this.queryParams.deptId = null
      }
    }
  },
  mounted() {
    let date = new Date()
    let year = date.getFullYear().toString()
    let month = date.getMonth() + 1
    this.queryParams.planDate = year + (Number(month) < 10 ? '0' + month : month)
    this.handlerInitList(this.queryParams)
  },
  methods: {
    // 初始化列表
    handlerInitList(queryParams) {
      // 数据总统计
      getStatisticsQueryList(queryParams).then(res => {
        this.init_list = res.data
      })
      // 数据总统计表头
      getStatisticsQueryListHeader(queryParams).then(res => {
        this.header_list = res.data
      })
      // 获取营销部
      getStatisticDept().then(res => {
        this.dept_list = res.data
      })
    },
    // 查询
    handlerSearch() {
      this.init_list = []
      this.header_list = []
      this.handlerInitList(this.queryParams)
    },
    // 导出
    handlerExportData() {
      this.$confirm('确定下载模板文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.size = 10000;
        var _that = this;
        /* 从表生成工作簿对象 */
        // 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去,
        var fix = document.querySelector('.el-table__fixed');
        getStatisticsQueryList(this.queryParams).then(res => {
          if (res.code == 200) {
            _that.tableData = res.data;
            _that.$nextTick(()=> {
              let wb;
              if (fix) {
                wb = XLSX.utils.table_to_book(document.querySelector('#out-table').removeChild(fix));
                document.querySelector('#out-table').appendChild(fix);
              } else {
                wb = XLSX.utils.table_to_book(document.querySelector('#out-table'));
              }
              /* 获取二进制字符串作为输出 */
              var wbout = XLSX.write(wb, {
                bookType: 'xlsx',
                bookSST: true,
                type: 'array'
              })
              FileSaver.saveAs(
                //Blob 对象表示一个不可变、原始数据的类文件对象。
                //Blob 表示的不一定是JavaScript原生格式的数据。
                //File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
                //返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
                new Blob([wbout], { type: 'application/octet-stream' }),
                //设置导出文件名称
                '指标进度导入模板.xlsx'
              )
            });
          } else {
            this.$message.error(res.msg);
          }
        })
      })
    }
  },
};
</script>

<style scoped lang="scss">
.contact {
  padding: 1px 20px 20px;
  box-sizing: border-box;
  background-color: #f5f8fa;
  min-height: calc(100vh - 85px);
  .input-box {
    display: flex;
    margin-top: 20px;
    flex-wrap: wrap;
  }

  .content-box {
    width: 100%;
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
  }

}
</style>

动态渲染表单

后端传递的数据分为 表头 和 表格信息

表头信息:

表格信息:

<div class="content-box">
      <el-table :data="init_list" max-height="700" id="out-table">
        <el-table-column label="一级目录" prop="firDirectory" align="center" width="120" fixed="left" />
        <el-table-column label="二级目录" prop="secDirectory" align="center" width="150" fixed="left" />
        <el-table-column label="三级目录" prop="thirdDirectory" align="center" width="200" fixed="left" />
        <el-table-column v-for="(item, index) in header_list" :key="index" :label="item" align="center">
          <template slot-scope="scope">
            <div v-for="(itm, idx) in scope.row.valueList" :key="idx">
              {{ itm[item] || 0 }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
        @pagination="handlerInitList" /> -->
    </div>

这次做的动态渲染表单 是表头 == 表格的key值 渲染出表头之后 item[表头] 就能找到相对应的值

前端导出表格 需要引入 file-saver 和 xmls 

  1. npm install file-saver --save

  2. npm install xmls --save

需要给el-table 添加一个id 

把代码复制一下就能用 有问题不懂的地方可以留言讨论

### 实现 Element UI 的 `el-table` 组件中合并单元格并导出 ExcelElement UI 中,可以通过自定义渲染函数来实现表格中的单元格合并功能。对于导出操作,则可以利用第三方库如 `xlsx` 或者使用浏览器内置 API 来完成。 #### 合并单元格 为了实现在特定条件下自动合并相邻相同内容的列,在初始化数据时需要遍历原始数组,并记录哪些行应该被跨越显示: ```javascript // 计算每一列的最大连续重复次数 function getSpanArr(data, prop) { let result = []; data.forEach((item, index) => { if (index === 0) { result.push(1); } else { const prevItem = data[index - 1]; if (prevItem[prop] === item[prop]) { result[index - 1]++; result.push(0); // 被合并则置零 } else { result.push(1); } } }); return result; } ``` 接着设置 `span-method` 属性给 `<el-table>` 标签,传入上述计算得到的结果作为参数控制实际展示效果[^2]: ```html <template> <div id="app"> <el-table :data="tableData" border style="width: 100%" :span-method="objectSpanMethod"> <!-- 表头 --> <el-table-column label="日期" width="180"> <template slot-scope="scope">{{ scope.row.date }}</template> </el-table-column> <el-table-column property="name" label="姓名"></el-table-column> <el-table-column property="address" label="地址"></el-table-column> </el-table> </div> </template> <script> export default { name: 'App', methods: { objectSpanMethod({ row, column, rowIndex, columnIndex }) { if (columnIndex === 0 || columnIndex === 1) { // 只处理前两列 return this.spanArr[rowIndex] ? [this.spanArr[rowIndex], 1] : [0, 0]; } }, }, }; </script> ``` #### 导出Excel文件 要将当前页面上的表格转换成 Excel 文件下载下来,一种简单的方式就是借助于 SheetJS 库 (`npm install xlsx`) 。这里给出一个完整的例子说明如何结合 Vue.js 和这个插件一起工作: ```javascript import XLSX from "xlsx"; methods: { exportTableToExcel() { var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'), {sheet:"Sheet JS"}); /* 获取二进制字符串作为输出 */ var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'array'}); try { FileSaver.saveAs(new Blob([wbout],{type:"application/octet-stream"}), 'test.xlsx'); } catch(e){if(typeof console!=='undefined')console.log(e,'FileSaver.js needed for client-side saving');} } }, mounted(){ require('file-saver'); } ``` 需要注意的是,这段代码假设有一个 ID 为 `out-table` 的 HTML table 存在于 DOM 结构当中;如果直接基于 element-ui 的 el-table 进行操作的话,可能还需要额外做些适配调整[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值