Vue implements multiple ways to export excel

There are many ways to export Excel in Vue, which can be realized through the front end, or through the cooperation of the front and back ends. Several common implementation methods will be introduced in detail below.

1. Front-end implementation method:

  • Use xlsxthe library: Use xlsxthe library to export data as an Excel file on the front end. First, you need to install xlsxthe library, and then introduce and use the library in the Vue component to process data and export Excel files. Here is a sample code:
    Using the xlsx library: xlsx is a JavaScript library for reading, parsing and writing Excel files. It provides a series of APIs to process Excel files. Using this library, you can convert the data into an Excel file and download it locally. This method is suitable for scenarios where Excel files are directly generated on the front end
<template>
  <div>
    <button @click="exportExcel">导出Excel</button>
  </div>
</template>

<script>
import XLSX from 'xlsx';

export default {
  methods: {
    exportExcel() {
      const data = [
        ['姓名', '年龄'],
        ['Alice', 20],
        ['Bob', 25],
        ['Charlie', 30]
      ];

      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, 'data.xlsx');
    }
  }
};
</script>

2. Implementation method of front-end and back-end cooperation:

  • Use the back-end interface to generate an Excel file: the front-end sends a request to the back-end interface, the back-end interface generates an Excel file and returns it to the front-end, and the front-end downloads it. The following is a sample code:
    Use front-end and back-end cooperation: In this method, the front-end initiates a request to the back-end, the back-end generates an Excel file and returns it to the front-end, and the front-end downloads the file to the local. You can use the axios library to initiate the request and use the Blob and a tags to download the file. This method is suitable for scenarios where data needs to be processed on the back end and Excel files generated

Front-end code:

<template>
  <div>
    <button @click="exportExcel">导出Excel</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    exportExcel() {
      axios.get('/api/export').then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'data.xlsx');
        document.body.appendChild(link);
        link.click();
      });
    }
  }
};
</script>

Backend code (using Node.js and Express framework):

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

app.get('/api/export', (req, res) => {
    
    
  const data = [
    ['姓名', '年龄'],
    ['Alice', 20],
    ['Bob', 25],
    ['Charlie', 30]
  ];

  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  const excelBuffer = XLSX.write(wb, {
    
     type: 'buffer', bookType: 'xlsx' });

  res.setHeader('Content-Disposition', 'attachment; filename=data.xlsx');
  res.type('application/octet-stream');
  res.send(excelBuffer);
});

app.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

3. Using FileSaver.jsthe library:`

FileSaver.js 是一个用于在浏览器中保存文件的JavaScript库。可以结合xlsx 库和FileSaver.js`library to export data to Excel files and download them locally. Here is a sample code:
Using the FileSaver.js library: FileSaver.js is a JavaScript library for saving files in the browser. Combined with the xlsx library and the FileSaver.js library, the data can be converted into an Excel file and downloaded to the local. This method uses the saveAs function provided by the FileSaver.js library to save the file. Applicable to scenarios where Excel files are directly generated on the front end and downloaded locally

<template>
  <div>
    <button @click="exportExcel">导出Excel</button>
  </div>
</template>

<script>
import XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  methods: {
    exportExcel() {
      const data = [
        ['姓名', '年龄'],
        ['Alice', 20],
        ['Bob', 25],
        ['Charlie', 30]
      ];

      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      const excelBuffer = XLSX.write(wb, { type: 'array', bookType: 'xlsx' });

      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
      saveAs(blob, 'data.xlsx');
    }
  }
};
</script>

4. Use html-table-to-excelthe library:

html-table-to-excelis a JavaScript library for exporting HTML tables to Excel files. Table data in Vue components can be exported to Excel files. Here is a sample code:
Using the html-table-to-excel library: html-table-to-excel is a JavaScript library for exporting HTML tables to Excel files. By converting the tabular data in the Vue component into an HTML table, and then using the html-table-to-excel library to export it as an Excel file. It is suitable for exporting the tabular data already rendered in the Vue component as an Excel file

<template>
  <div>
    <table id="data-table">
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.name">
          <td>{
   
   { item.name }}</td>
          <td>{
   
   { item.age }}</td>
        </tr>
      </tbody>
    </table>
    <button @click="exportExcel">导出Excel</button>
  </div>
</template>

<script>
import htmlTableToExcel from 'html-table-to-excel';

export default {
  data() {
    return {
      data: [
        { name: 'Alice', age: 20 },
        { name: 'Bob', age: 25 },
        { name: 'Charlie', age: 30 }
      ]
    };
  },
  methods: {
    exportExcel() {
      htmlTableToExcel('data-table', 'data');
    }
  }
};
</script>

The difference between the four methods:

  1. Using xlsxthe library: This method is to generate Excel files directly on the front end. You can use xlsxthe API provided by the library to convert the data into an Excel file, and then download it locally. The advantage of this method is that the generation process of the Excel file can be completely controlled at the front end, and the data can be processed and formatted. The disadvantage is that a large amount of data processing is required on the front end, which may affect performance for large amounts of data.

  2. Use front-end and back-end coordination: This method puts the generation process of the Excel file on the back-end. The front end initiates a request to the back end, the back end processes the data and generates an Excel file, and then returns the file to the front end for download. The advantage of this method is that the pressure of data processing can be placed on the backend, and the frontend only needs to process the logic of requesting and downloading files. The disadvantage is that it requires the cooperation of the front and back ends, which increases the workload of the back end.

  3. Using FileSaver.jsa library: This method is to directly generate an Excel file on the front end and download it. You can use xlsxthe library to convert the data into an Excel file, and then use the functions FileSaver.jsprovided by the library saveAsto save the file locally. The advantage of this method is that it is easy to use, does not require back-end participation, and can directly complete the generation and download of Excel files on the front-end. The downside is that it might affect performance for large amounts of data, since all processing happens on the front end.

  4. Using html-table-to-excelthe library: This method is to export the table data already rendered in the Vue component as an Excel file. You need to convert the tabular data in the Vue component into an HTML table, and then use html-table-to-excelthe library to export it as an Excel file. The advantage of this method is that it is simple and easy to use, without the need to use xlsxa library for data conversion, and directly export the table data as an Excel file. The disadvantage is that it only applies to the export of tabular data that has been rendered in the Vue component.

If you need to generate Excel files directly on the front end, you can choose to use xlsxa library or FileSaver.jslibrary. If you need to process data and generate Excel files at the back end, you can choose the method of front and back end cooperation. If you only need to export the table data that has been rendered in the Vue component as an Excel file, you can choose to use html-table-to-excelthe library. Choose an appropriate method according to specific needs to realize the function of exporting to Excel.

Guess you like

Origin blog.csdn.net/ACCPluzhiqi/article/details/132538408