From 642cad27475b8b49aa23c2cc1ad01dc1e6a1d318 Mon Sep 17 00:00:00 2001 From: vaishnav k <89403217+vaishnav4281@users.noreply.github.com> Date: Tue, 17 Dec 2024 23:27:54 +0530 Subject: [PATCH] Create CsvGenerator.tsx CSV Generator Purpose The CSV Generator component is designed for: Exporting Data: Allows users to download and save structured data (e.g., tables or datasets) in CSV format. Reusability: Can be reused across various features or pages, supporting any dataset passed via props. Dynamic Integration: Automatically detects headers and handles different data structures dynamically. User-Friendly Downloads: Enables quick and simple CSV file generation without relying on third-party libraries. --- src/components/CsvGenerator.tsx | 56 +++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/components/CsvGenerator.tsx diff --git a/src/components/CsvGenerator.tsx b/src/components/CsvGenerator.tsx new file mode 100644 index 0000000..ed7b957 --- /dev/null +++ b/src/components/CsvGenerator.tsx @@ -0,0 +1,56 @@ +import React from "react"; + +interface CsvGeneratorProps { + data: object[]; // Array of objects to convert to CSV + fileName?: string; // Name of the CSV file +} + +const CsvGenerator: React.FC = ({ data, fileName = "data.csv" }) => { + const generateCsv = () => { + if (!data || data.length === 0) { + alert("No data available to generate CSV."); + return; + } + + // Extract headers + const headers = Object.keys(data[0]); + const csvRows = []; + + // Add header row + csvRows.push(headers.join(",")); + + // Add data rows + data.forEach((row) => { + const values = headers.map((header) => { + const cell = row[header]; + return typeof cell === "string" ? `"${cell.replace(/"/g, '""')}"` : cell; + }); + csvRows.push(values.join(",")); + }); + + // Combine rows into a single string + const csvContent = csvRows.join("\n"); + + // Create a blob and a downloadable link + const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }); + const url = URL.createObjectURL(blob); + + const link = document.createElement("a"); + link.href = url; + link.download = fileName; + link.click(); + + URL.revokeObjectURL(url); // Clean up + }; + + return ( + + ); +}; + +export default CsvGenerator;