Exporting Vue Table Data to Excel Workbooks
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.