Skip to content

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.

The pattern for creating a Model from an Excel file involves two steps:

  1. Read the file as an ArrayBuffer
  2. Create a Model instance using Model.fromXlsx

The Model class is provided by @grid-is/spreadsheet-engine and handles parsing, formulas, and recalculation internally.

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>
);
}

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);
}

Now that you know how to create a Model, you can: