Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
2.6 kB
3
Indexable
Never
<template>
  <div>
    <button @click="downloadCSV">Download as CSV</button>
    <button @click="downloadExcel">Download as Excel</button>
    <button @click="downloadPDF">Download as PDF</button>
  </div>
</template>

<script>
import ExcelJS from 'exceljs';
import { jsPDF } from 'jspdf';

export default {
  props: {
    data: {
      type: Array,
      required: true
    },
    headers: {
      type: Array,
      required: true
    }
  },
  methods: {
    downloadCSV() {
      const csvContent = this.convertToCSV();
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', 'data.csv');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    convertToCSV() {
      const header = this.headers.join(',');
      const rows = this.data.map(row => this.headers.map(field => JSON.stringify(row[field])).join(','));
      return [header, ...rows].join('\r\n');
    },
    async downloadExcel() {
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Data');

      // Add headers
      worksheet.addRow(this.headers);

      // Add rows
      this.data.forEach(item => {
        worksheet.addRow(this.headers.map(header => item[header]));
      });

      // Create a buffer and download the file
      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', 'data.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    downloadPDF() {
      const doc = new jsPDF();
      const tableColumn = this.headers;
      const tableRows = [];

      // Add header to PDF
      tableRows.push(tableColumn);

      // Add data rows to PDF
      this.data.forEach(item => {
        tableRows.push(this.headers.map(header => item[header]));
      });

      // Set table properties and add to document
      doc.autoTable({
        head: [tableColumn],
        body: tableRows,
      });

      // Save the PDF
      doc.save('data.pdf');
    }
  }
};
</script>

<style scoped>
button {
  margin: 5px;
}
</style>
Leave a Comment