Vue 使用 XLSX+FileSaver 导出 excel 文件

2,789 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

A journey of a thousand miles begins with single step

背景

在此篇文章之前有了两篇关于 Vue 导出 excel 文件,分别是Vue 使用Export2Excel 导出 excel文件Vue 使用 Export2MultipleSheetExcel 导出多 Sheet excel文件。分别介绍了导出一般表格为 excel文件和多 Sheet excel文件的方式,那为什么还需要这篇文章呢?答案肯定是以上两种方式都不能满足当前的业务需求。

例如下图

复杂表格.jpg

思路

上图中的表格没有表头(业务需求必须这样展示),还有各种需要合并的单元格,按照之前文章的思路这样的表格导出确实非常棘手。但是我们换个思路来想,这个表格已经完成了 展示,能不能通过这个 tableDOM 节点中直接取出数据放在 excel 中呢?确实下面的方法就是这种思路,不需要我们考虑表格格式(像单元格合并,或者单元格是否可以编辑)的问题,就能实现导出为 excel 文件

使用

本文需要在上文的基础上进行,如果没有阅读上文,需要先安装下面的依赖包,若已经安装请跳过。

# use npm
npm install file-saver -S
npm install xlsx -S
npm install script-loader -D

# use yarn
yarn add file-saver xlsx
yarn add file-saver script-loader --dev

在项目中创建一个 vue 文件, 配置好路由方便测试,项目中使用的是elementUI组件库

在模板中

<template>
  <div class="dom-to-excel">
    <el-button type="primary" @click="exData">导出</el-button>
    <!-- 这个table的id导出时需要用到 -->
    <el-table
      :data="tableDataLegacy"
      id="legacy"
      border
      height="800"
      class="tableListGrid"
      :span-method="objectSpanMethod"
      :row-style="TableRowStyleLegacy">
      <el-table-column
        v-for="(col, index) in fieldListLegacy"
        :key="index"
        :prop="col.field"
        :label="col.label"
        :width="col.width"
        align="center"
        show-overflow-tooltip>
        <el-table-column
          v-for="(childCol, childindex) in col.child"
          :key="childindex"
          :prop="childCol.field"
          :label="childCol.label"
          align="center"
          show-overflow-tooltip>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
</template>

script中引入导出的方法和所需要的数据

import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { data } from '@/views/funs/data'

data函数中定义所需要的数据

mergeListLegacy: [],
fieldListLegacy: [],
tableDataLegacy: []

methods 中定义模板中绑定事件对应的方法,在该方法中完成导出

exData () {
  var wb = XLSX.utils.table_to_book(document.querySelector('#legacy'), { raw: true })
  var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '数据报表.xlsx')
  } catch (e) {
    if (typeof console !== 'undefined') {
      console.log(e, wbout)
    }
  }
  return wbout
}

在本文的导出中除了该导出方法时重点,还有后端返回的数据处理,以及如何进行动态合并的思想也是很值得品味的。有需要的小伙伴可以在代码案例中进行查看案例。

导出效果如下

效果.jpg

案例代码

XLSX + FileSaver 案例代码:gitee.com/yunxii/vue-…