import message from '@/components/ui/message'; import { Spin } from '@/components/ui/spin'; import request from '@/utils/request'; import classNames from 'classnames'; import React, { useEffect, useRef, useState } from 'react'; interface CSVData { rows: string[][]; headers: string[]; } interface FileViewerProps { className?: string; url: string; } const CSVFileViewer: React.FC = ({ url }) => { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(true); const containerRef = useRef(null); // const url = useGetDocumentUrl(); const parseCSV = (csvText: string): CSVData => { console.log('Parsing CSV data:', csvText); const lines = csvText.split('\n'); const headers = lines[0].split(',').map((header) => header.trim()); const rows = lines .slice(1) .map((line) => line.split(',').map((cell) => cell.trim())); return { headers, rows }; }; useEffect(() => { const loadCSV = async () => { try { const res = await request(url, { method: 'GET', responseType: 'blob', onError: () => { message.error('file load failed'); setIsLoading(false); }, }); // parse CSV file const reader = new FileReader(); reader.readAsText(res.data); reader.onload = () => { const parsedData = parseCSV(reader.result as string); console.log('file loaded successfully', reader.result); setData(parsedData); }; } catch (error) { message.error('CSV file parse failed'); console.error('Error loading CSV file:', error); } finally { setIsLoading(false); } }; loadCSV(); return () => { setData(null); }; }, [url]); return (
{isLoading ? (
) : data ? ( {data.headers.map((header, index) => ( ))} {data.rows.map((row, rowIndex) => ( {row.map((cell, cellIndex) => ( ))} ))}
{header}
{cell || '-'}
) : null}
); }; export default CSVFileViewer;