import { useState, useEffect } from "react"; import { useQuery } from "@tanstack/react-query"; import axios from "axios"; import * as XLSX from "xlsx"; type Props = { url?: string; }; export function ExcelPreview({ url }: Props) { const [sheets, setSheets] = useState<{ name: string; data: any[][] }[]>([]); const [activeSheet, setActiveSheet] = useState(0); const { data, isLoading, error, isError } = useQuery({ queryKey: ["excel", url], queryFn: () => axios.get(url!, { responseType: "arraybuffer" }), enabled: !!url, }); useEffect(() => { if (data?.data) { try { const workbook = XLSX.read(data.data, { type: "array" }); const sheetData = workbook.SheetNames.map((name) => { const worksheet = workbook.Sheets[name]; const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); return { name, data: jsonData as any[][] }; }); setSheets(sheetData); } catch (err) { } } }, [data]); if (!url) { return (
Excel 文件地址无效
); } if (isLoading) { return (
加载中...
); } if (isError) { return (
{error?.message || "加载失败"}
); } if (sheets.length === 0) { return (
Excel 文件为空或格式不正确
); } const currentSheet = sheets[activeSheet]; return (
{sheets.length > 1 && (
{sheets.map((sheet, index) => ( ))}
)}
{currentSheet.data.map((row, rowIndex) => ( {row.map((cell, cellIndex) => ( ))} ))}
{cell !== null && cell !== undefined ? String(cell) : ""}
); }