Untitled

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

<script>
import ExcelJS from 'exceljs';

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);
    }
  }
};
</script>

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