Papp Zoltán
Papp Zoltán

Reputation: 181

How to export all data from a primereact lazy loaded table?

I'd like export all data from a lazy loaded PrimeReact DataTable to CSV file. I can export one page to file but not all data from all page.

const dt = useRef<any>(null);

const exportCSV = (selectionOnly: boolean) => {
    dt.current.exportCSV({ selectionOnly });
};

const header = (
    <div className="flex align-items-center justify-content-end gap-2">
        <Button type="button" icon="pi pi-file" rounded onClick={() => exportCSV(false)} data-pr-tooltip="CSV" />
    </div>
);

<DataTable value={channelsValues}
    ref={dt}
    header={header}
...

Please help me.

Upvotes: 1

Views: 944

Answers (1)

Papp Zolt&#225;n
Papp Zolt&#225;n

Reputation: 181

POE AI answered my question:

function convertToCSV(data: any) {
    const rows = [];
    const headers = Object.keys(data[0]);

    // Add header row
    rows.push(headers.join(','));

    // Add data rows
    data.forEach((item: any) => {
        const values = headers.map(header => item[header]);
        rows.push(values.join(','));
    });

    return rows.join('\n');
}

function downloadCSVFile(data: any, filename: string) {
    const blob = new Blob([data], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

I need fetch all data from the server and then convert it to csv and give back it in a download link at client side.

Upvotes: 1

Related Questions