docs.sheetjs.com/docz/static/mui/table/App.tsx
2024-06-13 00:31:40 -04:00

48 lines
1.4 KiB
TypeScript

import { TableContainer, Table, TableRow, TableCell, TableBody, TableHead } from '@mui/material';
import { WorkBook, WorkSheet, read, utils, writeFileXLSX } from "xlsx";
import { useRef, useState, useEffect } from "react";
import './App.css'
interface President {
Name: string;
Index: number;
}
function App() {
const tbl = useRef<HTMLTableElement>(null);
const xport = () => {
const wb: WorkBook = utils.table_to_book(tbl.current);
writeFileXLSX(wb, "SheetJSMaterialUI.xlsx");
};
const [pres, setPres] = useState<President[]>([]);
useEffect(() => {
let active = true;
(async() => {
const ab: ArrayBuffer = await (await fetch("https://docs.sheetjs.com/pres.xlsx")).arrayBuffer();
const wb: WorkBook = read(ab);
const ws: WorkSheet = wb.Sheets[wb.SheetNames[0]];
const aoo: President[] = utils.sheet_to_json<President>(ws);
if(active) setPres(aoo);
})();
return () => { active = false };
}, []);
return ( <>
<button onClick={xport}>Export</button>
<TableContainer><Table ref={tbl}>
<TableHead><TableRow><TableCell>Name</TableCell><TableCell>Index</TableCell></TableRow></TableHead>
<TableBody>
{pres.map((row, idx) => (
<TableRow key={idx}>
<TableCell>{row.Name}</TableCell>
<TableCell>{row.Index}</TableCell>
</TableRow>
))}
</TableBody>
</Table></TableContainer>
</> );
}
export default App