We use cookies to enhance your experience on the site
CodeWorlds

Export Data - CSV/PDF Reports

Exporting data to CSV and PDF.

CSV Export 📄

1function exportToCSV(data: any[], filename: string) {
2  const headers = Object.keys(data[0]).join(',');
3  const rows = data.map(row => Object.values(row).join(','));
4  const csv = [headers, ...rows].join('
5');
6
7  const blob = new Blob([csv], { type: 'text/csv' });
8  const url = URL.createObjectURL(blob);
9  const link = document.createElement('a');
10  link.href = url;
11  link.download = filename;
12  link.click();
13}
14
15function DataTable({ data }: { data: any[] }) {
16  return (
17    <div>
18      <button
19        onClick={() => exportToCSV(data, 'report.csv')}
20        className="bg-green-600 text-white px-4 py-2 rounded mb-4"
21      >
22        Export CSV
23      </button>
24      <table className="w-full border">
25        {/* Table content */}
26      </table>
27    </div>
28  );
29}

PDF Export 📑

1npm install jspdf jspdf-autotable
1import jsPDF from 'jspdf';
2import autoTable from 'jspdf-autotable';
3
4function exportToPDF(data: any[], filename: string) {
5  const doc = new jsPDF();
6
7  doc.text('Analytics Report', 14, 15);
8
9  autoTable(doc, {
10    head: [Object.keys(data[0])],
11    body: data.map(row => Object.values(row))
12  });
13
14  doc.save(filename);
15}

See you next time! 🚀

Go to CodeWorlds