当前位置:首页 > VUE

vue实现导出excel表格

2026-02-22 21:13:26VUE

Vue 实现导出 Excel 表格的方法

使用 xlsx 库

安装 xlsx 库:

npm install xlsx

在 Vue 组件中引入并使用:

import * as XLSX from 'xlsx';

export default {
  methods: {
    exportToExcel() {
      const data = [
        ['Name', 'Age', 'Email'],
        ['Alice', 25, 'alice@example.com'],
        ['Bob', 30, 'bob@example.com']
      ];
      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, 'export.xlsx');
    }
  }
}

使用 vue-json-excel 插件

安装插件:

npm install vue-json-excel

在 Vue 中注册并使用:

import JsonExcel from 'vue-json-excel';

export default {
  components: {
    JsonExcel
  },
  data() {
    return {
      json_data: [
        { name: 'Alice', age: 25, email: 'alice@example.com' },
        { name: 'Bob', age: 30, email: 'bob@example.com' }
      ],
      fields: {
        'Name': 'name',
        'Age': 'age',
        'Email': 'email'
      }
    }
  }
}

模板中使用:

<download-excel
  :data="json_data"
  :fields="fields"
  name="export.xlsx">
  Download Excel
</download-excel>

使用 FileSaver 和 xlsx

结合 FileSaver 实现下载:

npm install file-saver xlsx

实现代码:

import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';

export default {
  methods: {
    exportExcel() {
      const data = [
        { name: 'Alice', age: 25, email: 'alice@example.com' },
        { name: 'Bob', age: 30, email: 'bob@example.com' }
      ];
      const worksheet = XLSX.utils.json_to_sheet(data);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      saveAs(blob, 'export.xlsx');
    }
  }
}

后端生成 Excel 前端下载

如果数据量较大,建议后端生成 Excel 文件,前端通过接口下载:

export default {
  methods: {
    downloadExcel() {
      window.location.href = '/api/export-excel';
    }
  }
}

后端示例(Node.js Express):

const express = require('express');
const XLSX = require('xlsx');
const app = express();

app.get('/api/export-excel', (req, res) => {
  const data = [
    ['Name', 'Age', 'Email'],
    ['Alice', 25, 'alice@example.com'],
    ['Bob', 30, 'bob@example.com']
  ];
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  const buf = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
  res.setHeader('Content-Disposition', 'attachment; filename=export.xlsx');
  res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.send(buf);
});

样式定制

如需添加样式,可以使用 xlsx-style 库:

npm install xlsx-style

示例代码:

import * as XLSX from 'xlsx-style';

export default {
  methods: {
    exportStyledExcel() {
      const ws = {
        '!ref': 'A1:C3',
        A1: { t: 's', v: 'Name', s: { font: { bold: true } } },
        B1: { t: 's', v: 'Age', s: { font: { bold: true } } },
        C1: { t: 's', v: 'Email', s: { font: { bold: true } } },
        A2: { t: 's', v: 'Alice' },
        B2: { t: 'n', v: 25 },
        C2: { t: 's', v: 'alice@example.com' }
      };
      const wb = { SheetNames: ['Sheet1'], Sheets: { Sheet1: ws } };
      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      saveAs(blob, 'styled-export.xlsx');
    }
  }
}

大数据量分片处理

对于大数据量导出,建议分片处理:

vue实现导出excel表格

export default {
  methods: {
    async exportLargeData() {
      const chunkSize = 10000;
      let offset = 0;
      const allData = [];

      while (true) {
        const chunk = await this.fetchData(offset, chunkSize);
        if (chunk.length === 0) break;
        allData.push(...chunk);
        offset += chunkSize;
      }

      const ws = XLSX.utils.json_to_sheet(allData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, 'large-export.xlsx');
    },

    fetchData(offset, limit) {
      // 实现数据获取逻辑
    }
  }
}

以上方法覆盖了 Vue 中实现 Excel 导出的常见场景,从简单表格到大数据量处理,以及样式定制等需求。根据实际项目需求选择合适的方法即可。

标签: 表格vue
分享给朋友:

相关文章

vue实现app

vue实现app

Vue 实现 App 的常见方法 使用 Vue 开发移动端 App 主要有两种主流方案:混合开发(Hybrid)和原生渲染。以下是具体实现方式和工具链: 混合开发方案(WebView 嵌入) 通过…

jquery实现vue

jquery实现vue

jQuery 和 Vue.js 是两种不同理念的前端工具,jQuery 以 DOM 操作和事件驱动为核心,而 Vue.js 是数据驱动的现代化框架。如果想用 jQuery 实现类似 Vue 的功能(如…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…

vue实现增加

vue实现增加

实现 Vue 中的新增功能 在 Vue 中实现新增功能通常涉及数据绑定、表单处理和状态管理。以下是几种常见的实现方式: 数据绑定与列表渲染 通过 v-model 绑定表单输入,使用数组的 push…

vue 实现 confirm

vue 实现 confirm

实现确认对话框的方法 在Vue中实现确认对话框可以通过多种方式完成,包括使用内置组件、第三方库或自定义组件。 使用浏览器原生confirm 最简单的实现方式是直接调用浏览器原生的confirm方法。…

vue 实现templateurl

vue 实现templateurl

在 Vue 中,templateUrl 是 Angular 中的一个概念,用于指定外部 HTML 文件作为模板。Vue 本身不直接支持 templateUrl,但可以通过以下方法实现类似功能: 使用…