Loading spreadsheets
To use the SpreadsheetEditor component, you need to provide a model prop. This guide shows you how to create a Model from .xlsx files.
Basic pattern
Section titled “Basic pattern”The pattern for creating a Model from an Excel file involves two steps:
- Read the file as an
ArrayBuffer - Create a
Modelinstance usingModel.fromXlsx
The Model class is provided by @grid-is/spreadsheet-engine and handles parsing, formulas, and recalculation internally.
Loading from a file upload
Section titled “Loading from a file upload”Here’s a complete example of loading an Excel file from a file input. Create a React app (see quickstart) and put this in App.tsx:
import { useState, useEffect } from "react";import { Model } from "@grid-is/spreadsheet-engine";import { SpreadsheetEditor } from "@grid-is/spreadsheet-editor";import "@grid-is/spreadsheet-editor/style.css";
export default function App() { const [file, setFile] = useState<File | null>(null); const [model, setModel] = useState<Model | null>(null);
useEffect(() => { if (!file) { setModel(null); return; } let cancelled = false; (async () => { try { await Model.preconditions; const m = await Model.fromXlsx(await file.arrayBuffer(), file.name); if (!cancelled) setModel(m); } catch (error) { console.error("Failed to load file:", error); } })(); return () => { cancelled = true; }; }, [file]);
if (!model) { return ( <input type="file" accept=".xlsx" onChange={(e) => setFile(e.target.files?.[0] ?? null)} /> ); }
return ( <div style={{ width: "100vw", height: "100vh" }}> <SpreadsheetEditor model={model} /> </div> );}Error handling
Section titled “Error handling”Always handle potential errors when loading files:
try { await Model.preconditions; const arrayBuffer = await file.arrayBuffer(); const m = await Model.fromXlsx(arrayBuffer, file.name);
setModel(m); setError(null);} catch (error) { setError("Failed to load file. Please make sure it's a valid .xlsx file."); console.error("File loading error:", error);}Next steps
Section titled “Next steps”Now that you know how to create a Model, you can:
- React to user interactions with the onChange callback
- Control the editor programmatically
- Explore the complete API reference