英文:
How to export all data from a primereact lazy loaded table?
问题
我想要从一个惰性加载的 PrimeReact DataTable 中导出所有数据到 CSV 文件。我可以将一页数据导出到文件,但无法导出所有页面的所有数据。
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}
...
请帮助我。
英文:
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.
答案1
得分: 1
POE AI回答了我的问题:
function convertToCSV(data: any) {
    const rows = [];
    const headers = Object.keys(data[0]);
    // 添加标题行
    rows.push(headers.join(','));
    // 添加数据行
    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);
}
我需要从服务器获取所有数据,然后将其转换为CSV格式,并在客户端提供下载链接。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论