返回

让信息高效流动,直观呈现:基于 Vue 的 Web 端和 Electron 桌面端导出 Excel 表格

前端

在 Web 端中导出 Excel 表格

利用浏览器提供的 API 和 Vue 生态中的工具,可以在 Web 端轻松导出 Excel 表格。下面以一个示例来说明如何实现:

import Vue from 'vue';
import { export_json_to_excel } from 'vue-export-excel';

Vue.component('excel-export', {
  data() {
    return {
      tableData: [
        { name: 'John Doe', age: 30, city: 'New York' },
        { name: 'Jane Smith', age: 25, city: 'London' },
        { name: 'Michael Jones', age: 40, city: 'Paris' }
      ]
    };
  },
  methods: {
    exportExcel() {
      export_json_to_excel(this.tableData, {
        name: 'my-data',
        headers: ['Name', 'Age', 'City']
      });
    }
  },
  template: '<button @click="exportExcel">Export to Excel</button>'
});

在 HTML 文件中,使用 excel-export 组件即可轻松导出 Excel 表格。

在 Electron 桌面端导出 Excel 表格

Electron 桌面端应用程序可以与操作系统的文件系统进行交互,因此也可以导出 Excel 表格。下面以一个示例来说明如何实现:

const { dialog, app } = require('electron');
const fs = require('fs');
const XLSX = require('xlsx');

const exportExcel = () => {
  const data = [
    { name: 'John Doe', age: 30, city: 'New York' },
    { name: 'Jane Smith', age: 25, city: 'London' },
    { name: 'Michael Jones', age: 40, city: 'Paris' }
  ];

  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(data);
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  const filePath = dialog.showSaveDialogSync(app.mainWindow, {
    title: '导出 Excel 表格',
    filters: [{ name: 'Excel 文件', extensions: ['xlsx'] }]
  });

  if (filePath) {
    XLSX.writeFile(wb, filePath);
  }
};

在 HTML 文件中,使用按钮调用 exportExcel() 函数即可导出 Excel 表格。

无论是在 Web 端还是在 Electron 桌面端,基于 Vue 开发的应用程序都可以轻松实现 Excel 表格的导出,满足不同用户的需求,让信息高效流动,直观呈现。