Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Exporting Vue Table Data to Excel Workbooks

Tech 1

To generate spreadsheet files directly from a Vue data grid, integrate axios for network requests and xlsx for file generation. Begin by installing the required packages:

npm install axios xlsx

Construct a Vue component that renders the dataset and includes a trigger for the export operation. The template utilizes Ant Design Vue table components, mapping dynamic colums and binding the dataset to the grid.

<template>
  <div class="table-container">
    <a-button type="primary" @click="downloadSpreadsheet" style="margin-bottom: 1rem;">
      Save as Excel
    </a-button>
    <a-table
      :data-source="rowEntries"
      :columns="fieldConfig"
      bordered
      size="middle"
      row-key="identifier"
    />
  </div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      rowEntries: [],
      fieldConfig: [
        { title: 'Identifier', dataIndex: 'identifier' },
        { title: 'Full Name', dataIndex: 'fullName' },
        { title: 'Department', dataIndex: 'department' },
        { title: 'Role', dataIndex: 'role' }
      ],
    };
  },
  created() {
    this.loadRecords();
  },
  methods: {
    async loadRecords() {
      try {
        const response = await axios.get('/api/v1/records');
        this.rowEntries = Array.isArray(response.data) ? response.data : [];
      } catch (err) {
        console.error('Failed to retrieve dataset:', err);
      }
    },
    downloadSpreadsheet() {
      if (!this.rowEntries.length) {
        console.warn('No records available to export.');
        return;
      }

      const worksheet = XLSX.utils.json_to_sheet(this.rowEntries);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Data Export');

      const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(blob);
      downloadLink.download = `export_${Date.now()}.xlsx`;
      downloadLink.click();
      URL.revokeObjectURL(downloadLink.href);
    },
  },
};
</script>

The backend endpoint must return a standardized JSON array matching the column definitions. The export routine transforms the JavaScript objects into a spreadsheet sheet object using json_to_sheet, attaches it to a new workbook instance, and serializes it as an array buffer. This binary data is wrapped in a Blob with the appropriate MIME type, triggering a browser-initiaetd download via a temporary anchor element. Memory is freed immediately after the click by revoking the object URL. Adjust the API endpoint and column mapping to align with your specific backend schema. Ensure cross-origin resource sharing (CORS) policies permit requests from the frontend domain.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.