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/apiary 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:
import { useState, useEffect } from "react";import { Model } from "@grid-is/apiary";import { SpreadsheetEditor } from "@grid-is/editor-react";
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:
- Render the editor in your application
- React to user interactions with the onChange callback
- Control the editor programmatically
- Explore the complete API reference