import React, { useState } from "react"; import { Dropdown } from "react-bootstrap"; import { Download } from "react-bootstrap-icons"; const Export = ({ columns, data, filename = "export" }) => { const [showExportDropdown, setShowExportDropdown] = useState(false); const [exportColumns, setExportColumns] = useState( columns.map(col => ({ ...col, show: true })) ); const handleColumnToggle = (columnKey) => { const updatedColumns = exportColumns.map(col => col.key === columnKey ? { ...col, show: !col.show } : col ); setExportColumns(updatedColumns); }; const handleCancel = () => { setExportColumns(columns.map(col => ({ ...col, show: true }))); setShowExportDropdown(false); }; const generateCSV = () => { const visibleColumns = exportColumns.filter(col => col.show); const headers = visibleColumns.map(col => col.label).join(','); const rows = data.map(row => visibleColumns.map(col => { const value = row[col.key]; // Handle values that contain commas by wrapping in quotes return typeof value === 'string' && value.includes(',') ? `"${value}"` : value; }).join(',') ).join('\n'); const csvContent = `${headers}\n${rows}`; downloadFile(csvContent, `${filename}.csv`, 'text/csv'); }; const generateExcel = () => { const visibleColumns = exportColumns.filter(col => col.show); const headers = visibleColumns.map(col => col.label); const rows = data.map(row => visibleColumns.map(col => row[col.key]) ); // Create a simple Excel-like CSV with BOM for Excel compatibility const excelContent = '\ufeff' + [headers, ...rows] .map(row => row.map(cell => typeof cell === 'string' && (cell.includes(',') || cell.includes('"') || cell.includes('\n')) ? `"${cell.replace(/"/g, '""')}"` : cell ).join(',')) .join('\n'); downloadFile(excelContent, `${filename}.csv`, 'text/csv'); }; const generatePDF = () => { const visibleColumns = exportColumns.filter(col => col.show); // Create a simple HTML table for PDF generation const tableHTML = ` ${visibleColumns.map(col => ``).join('')} ${data.map(row => ` ${visibleColumns.map(col => ``).join('')} `).join('')}
${col.label}
${row[col.key] || ''}
`; // Use browser's print functionality to generate PDF const printWindow = window.open('', '_blank'); printWindow.document.write(tableHTML); printWindow.document.close(); printWindow.print(); }; const downloadFile = (content, filename, mimeType) => { const blob = new Blob([content], { type: mimeType }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }; const customExportMenu = React.forwardRef( ({ children, style, className, 'aria-labelledby': labeledBy }, ref) => { return (
Export Options
Select Columns:
{exportColumns.map((column) => (
handleColumnToggle(column.key)} />
))}
); }, ); return ( setShowExportDropdown(!showExportDropdown)} autoClose={false} > Export ); }; export default Export;