To design a spreadsheet program, work from the calculation model outward: decide the user-facing formula behavior, then build a dependency graph and recalculation engine, then layer the interface and file format on top. The key condition is that you design the evaluation model before any grid code is written, because nearly every other decision—storage layout, undo, collaboration, even how fast the cursor feels—is downstream of how you represent a cell as a formula, a value, or both at once.

That order isn't obvious from the outside. A spreadsheet looks like a grid with typing in it, and plenty of hobby projects start by drawing a table and get stuck two months later when =A1+1 resolves to the wrong value after a delete, or when undo silently corrupts a chain of formulas. This guide lays out a design sequence that avoids those traps, with the mechanisms, trade-offs, and failure cases you'll actually hit. It assumes you're building either a real product or a serious learning project; the depth scales down, but the order stays the same.

Start with the physical model, not the screen

Before diagrams, answer one question in writing: what is a cell?

In Excel and Google Sheets, a cell has a formula (text starting with =), a displayed value (the result of evaluating the formula, or a literal), and formatting. Those three lives are separate. A cell containing =2+3 stores the five characters of the formula and a cached numeric 5; the grid shows 5, the formula bar shows the formula. Google Sheets exposes the duality through FORMULA() and TO_TEXT(), and both major products recalculate lazily in some contexts and eagerly in others.

Your design alternatives, roughly:

Value-only cells (the earliest VisiCalc-style approach, where each cell holds a number or expression). Simple, but editors and error messages become awkward because there's no place to keep the original formula text. Formula + cached value (the Excel and Sheets model). You store both, mark the cache dirty when dependencies change, and recalc on demand or on a trigger. This is the mainstream choice and the one I'd recommend for almost any general-purpose spreadsheet. Formula-only, evaluate on every render. Attractive for tiny sheets, catastrophic at scale—re-evaluating 50,000 formulas on each keystroke is the classic hobby-project performance cliff.

Write this decision down, along with your literal types (numbers, text, booleans, error values, empty), your date representation (Excel historically used serial day numbers with a 1900 leap-year quirk; modern designs often use explicit types), and your text encoding. These choices are hard to reverse later because file formats and user expectations calcify around them.

Specify formula semantics before you build the engine

The single biggest source of "my spreadsheet program is subtly wrong" bugs is underspecified formula semantics. Before coding, nail down at least these:

Reference syntax and range operators. A1 style versus R1C1 style versus a structured model. A1 is what users expect; internally, many implementations convert to (row, column) indices immediately and only render A1 in the UI. Ranges need a half-open or inclusive convention — declare it once and never mix.

Relative versus absolute references. A1 shifts when copied; $A$1 doesn't; $A1 fixes the column. This is a copy/paste transformation, not an evaluation behavior: the formula string is rewritten on paste. Decide precisely how the rewrite handles ranges and multi-sheet references, and test copying a formula across a merged region, because that's where naive implementations break.

Empty cells versus zero. In Excel and Sheets, a reference to an empty cell in an arithmetic context behaves as 0, but ISBLANK still reports true and concatenation yields an empty string. If you and a collaborator disagree about this, your spreadsheets will disagree with Excel on real files.

Error values as first-class data. #DIV/0!, #VALUE!, #REF!, #NAME?, #N/A propagate through formula chains in defined ways. Errors are not exceptions—they're values that flow. Decide the propagation rule up front (typically: any operand that is an error yields that error, with the leftmost error often winning).

Circular references. Define what happens when A1 = B1 and B1 = A1 + 1. Excel reports a circular reference warning and, depending on settings, iterates to a limit or shows zeros. If you don't decide, you'll ship an infinite loop.

Evaluation order for side-effecting functions. RAND(), NOW(), and volatile functions break pure dependency reasoning. A clean design marks volatile functions and recalculates anything downstream on every recalc pass, but this makes recalculation cost unpredictable. Note that limit now.

Numeric precision. IEEE 754 doubles are the near-universal choice and will produce 0.1 + 0.2 = 0.30000000000000004-style artifacts that users report as bugs. Decide whether to round for display only (correct) or in storage (dangerous), and how your formatting layer hides the artifacts.

Get these wrong and no amount of UI polish saves you; users will notice on day one that pasting a formula produces different results than their previous tool.

Model dependencies as a graph

A spreadsheet is a computation graph disguised as a grid. Each formula cell is a node; each reference to another cell or range is a directed edge. The classic implementation is a topological sort of the graph, updated incrementally as formulas change.

The naive approach—recompute every formula top to bottom, row by row, on every edit—works for a toy and fails around a few thousand formulas. It's also wrong if a formula in row 1 references row 10, because the row-order pass evaluates with a stale value.

The mainstream design:

1: Dependency extraction. Parse each formula's references (single cells and ranges, across sheets), store them per cell. 2: Dirty propagation. When a cell changes, mark its direct dependents dirty, transitively. For a range reference, dependents are cells intersecting the range—which means the graph node for a range is itself a set of edges, or you materialize per-cell edges at parse time. 3: Topological recalculation. Only dirty cells are visited, in an order that respects edges. For dense range dependencies (sum over column A, repeated in column B), a node-per-range-plus-node-per-formula hybrid keeps the edge count manageable.

Real products go further: Excel's calculation engine distinguishes dependencies and precedents, supports iterative calculation modes for intentional circularity, and exposes F9-style full recalculation when incremental state drifts. Google Sheets recalculates on server-side infrastructure and streams results; the dependency model is internal but must handle array formulas, which produce ranges as outputs and complicate edges.

Failure mode: dependency graph staleness. If a bug in your dependency extraction misses a reference (say, an indirect reference via a named range or a string lookup), recalculation silently skips a cell and shows stale values. Include a "hard recalc" path that parses every formula and rebuilds the graph from scratch; expose it in the UI and use it in tests after every batch operation.

Recalculation strategy: eager, lazy, and hybrid

You have three practical strategies:

Eager recalculation: evaluate all dirty cells immediately on each edit and render fresh. Simple, predictable, and fine for small sheets. It becomes laggy on large ones and makes batch edits (fill down 10,000 rows) pay 10,000 recalcs unless you defer. Lazy recalculation: mark cells dirty and compute on access, typically on render or when a cell's value is requested. This makes editing fast and rendering the slow path; it distributes cost to the user's scroll position, which some users find worse than a stall on edit. Hybrid: defer recalculation within a single UI event (batch), then evaluate dirty cells once per frame or once per interaction, with a hard recalculation budget. If the budget is exceeded, background it and show stale values with an indicator.

For a new design, I'd start eager-per-event with a batch window and a hard recalculation budget, because it's easiest to make correct and easiest to test. Instrument the budget early—"recalc took 480 ms for 12,000 cells" is a number you'll need when deciding whether to go lazy.

Choose a storage layout after the model is settled

Three shapes dominate:

Cell map (sparse). A dictionary keyed by (sheet, row, col) to a cell record. Scales well with mostly-empty grids, handles inserts and deletes with occasional reindexing (or key shifts), and maps cleanly onto the dependency graph. The downside is memory overhead per record and cache-unfriendly iteration over ranges.

Dense 2D arrays with banded metadata. Store row blocks or columns as arrays, with sparse overlays for formatted or formula-bearing cells. This is the classic performance layout and what much of the engineered-in-C++ spreadsheet world uses. Inserts and deletes renumber blocks; gets fast for range scans. More engineering.

Columnar. Per-column arrays with per-cell presence bits. Good for large analytic sheets and operations like sum over a column; awkward for row-oriented operations and arbitrary range formatting.

The choice interacts with your dependency model: a sparse map makes "iterate dependents of a range" a scan unless you keep a range-to-cells index. Pick one representation, write the adapter boundary, and keep it narrow. If you get this wrong, every other component inherits the pain; if you keep the interface small (get/set/delete/iterate-range), you can swap implementations later.

This is also where you make the classic cost trade-off explicit. For a workbook with 1,000,000 potentially populated cells but only 5,000 actually used, the sparse map is roughly two orders of magnitude leaner in memory; for a densely filled 100,000 × 50 grid, banded blocks win on scan speed. Write down your expected workload before choosing.

Sheets, ranges, and the sparse-data reality

Multi-sheet workbooks with cross-sheet references (Sheet2!A1) mean your key becomes (sheet, row, col) and your dependency graph spans sheets. Deletion of a sheet invalidates all references to it; #REF! is the standard result. Renaming a sheet must rewrite formulas referencing it—a nontrivial string transformation if you support 3D references like Sheet1:Sheet3!A1, which Excel does and plenty of clones don't.

Named ranges are worth designing in early even if you ship them late: they're user-facing aliases that the parser resolves, and they materially affect how dependencies are extracted and how formulas are rewritten on copy. A named range that resolves to a non-contiguous region (Excel allows those, resolving to the union in some contexts and to an error in others) is a design decision, not a feature.

The UI and interaction layer

Spreadsheet interaction is a surprisingly deep well, and the grid should be treated as a view over the model, never as the model.

The formula bar. The standard model is: the grid shows the cached value, the formula bar shows the formula. Editing in the grid for a formula cell typically opens the formula editor—either in place or in the bar—and commits only on explicit enter, not on blur, because blur-commit causes data loss with tab navigation. Decision point: does typing = in a cell switch it into formula-edit mode with the rest of the content preserved? Both mainstream tools accept = as the first character as the trigger.

Editing modes and commits. Design edit sessions as transactions: begin, possibly abort (Escape), and commit (Enter or Tab). Mid-edit, nothing should reach the dependency graph except preview recalculation for the edited cell's own formula if you support live results. Commit batches: the edit, the copy, the fill, and the formatting go in as one unit so undo reverses them together.

Selection and ranges. Selection is a first-class model object—ranges over sheets, multi-range unions, and the active cell within. Pointer capture, keyboard navigation, and copy/paste all operate on selection state. Keep selection in a separate store from cell data; serializing selection into the data model produces a spreadsheet where selecting corrupts undo.

Fill and drag-fill. Autofill series detection (dates, weekdays, numeric patterns) is a surprising quantity of product logic. Pasting formulas down needs relative-reference rewriting; dragging across a range needs the same. Build it on the copy/paste rewrite engine from your semantics work, not as a separate code path.

Autosave and conflict of edits. If you autosave, you need a dirty-record policy and a recover path. Spreadsheet users treat the grid as the document; losing ten minutes of typed formulas to a bad autosave implementation is the worst bug class in the product.

Undo, transactions, and recalculation interplay

Undo in a spreadsheet is not a simple text-editor undo. The standard design: every user action produces a transaction record containing the inverse patch — old cell contents, old formatting, old selection. Because recalculation changes displayed values, undo must re-enter the inputs (formulas and literals), not the outputs.

The tricky part: an undo of a formula paste must undo every rewritten formula in the batch atomically. If the batch is partially applied and the inverse patch has to recompute which cells were changed, you're reconstructing intent; store the touched-cell set in the transaction. Keep transactions bounded—some implementations cap the stack at a few hundred entries in session to bound memory, which is acceptable.

Failure mode: a dependency-graph bug plus undo produces silent corruption, because undo returns values that don't match the formulas. Test undo by round-tripping operations and comparing full workbooks, not spot checks.

File format and compatibility from day one

If your spreadsheet program will open other tools' files, you're adopting their semantics, not just their syntax. .xlsx is the practical interop target; nobody reimplementing that will match Excel's full formula set, but partial import with explicit fallbacks is the common path. Specify now:

Which formulas you support, and what happens to the rest on import: preserve as opaque text with a warning, calculate to a value and lose the formula, or show #NAME?. Shared strings, dates, and the numeric precision of imported cells. Your own native format's versioning scheme.

For your native format, text-based JSON with a schema, or a zip of a manifest plus parts, are both reasonable. The discipline that matters is schema version plus migration tests from every prior version.

If you choose CSV as the export format, write down what CSV cannot express—formulas, types, merged cells—and be honest in the UI rather than silently degrading.

Performance, correctness tests, and release checks

Instrument three paths: recalculation time per batch, render time per frame for a visible viewport, and memory per workbook tier. Wiring a harness early lets you answer cost questions with numbers rather than guesses.

Design a correctness suite around semantics, not around the UI:

Reference rewriting matrix: relative, absolute, mixed references across copy, fill, paste, and multi-sheet targets. Recalculation suite: chains, diamonds, dense ranges, volatiles, and circular references with both the iterating mode and the error mode. Empty and zero semantics against Excel-compatible expectations. Error propagation matrices. Import round-trips for each supported subset. Undo round-trips for each mutation operation.

A simple success check: build a small benchmark workbook—say, 20,000 populated cells, 5,000 of them formulas with chains three levels deep—and treat "recalc under 100 ms" as your working budget. If you blow it, the usual causes in order are: recomputing clean cells, missing dependency information, or repeated graph rebuilds per edit.

Stop condition. If you find yourself needing to match Excel's full function library, its exact floating-point quirks, and its recalculation semantics for arbitrary imported files, that is a specification-research project rather than a design exercise. Bring in a product or engineering manager to scope the compatibility surface explicitly, rather than silently expanding the backlog.

Design decisions that tend to be made too late

A few design choices look like implementation details until they escalate:

Volatile function policy. NOW() and RAND() are marked volatile; define when they refresh and whether they participate in convergence-based recalc. If you add them "quickly," you'll be redesigning recalculation scheduling later. Array formulas and spills. Dynamic arrays (results spilling into adjacent cells) change dependency semantics; if you plan them, reserve the concept and design the editor path now. Collaborative editing. A spreadsheet that's shared live needs a conflict model between edits, and spreadsheet semantics make last-writer-wins bad and OT/CRDT non-trivial because a formula edit changes the recalculation graph for other users. If shared editing is a product requirement, design cell identity and operational history now —retrofitting tends to require rewriting the storage layer. Print layout. Page breaks, print ranges, and scaling are a sibling storage problem to the cell grid and frequently a late addition. It's inexpensive to reserve a page-layout section in the format schema; it's expensive to migrate files and redesign the UI later.

What "done" looks like for a first release

A first shippable version needs consistency more than breadth: a stable formula subset with declared semantics, a correct dependency-based recalculation path, batch undo, reliable copy/paste reference rewriting, a file format with a version, and a test suite that runs the reference and recalculation matrices. Functions can grow indefinitely; correctness in the core has to be there before function count means anything.

The biggest predictor of whether a spreadsheet program feels right is whether the model handles the mundane operations—paste, fill down, delete a row a formula depended on, undo past a format paste—by the same mechanism instead of special cases. Build the core behavior once and check it in the tests; the rest is surface area.

FAQ

Do I need a dependency graph if my sheets are small?

No—under a few thousand formulas, a top-to-bottom recalculation in the right order (parse formulas, resolve references to a topological order) will be fast enough. The graph earns its keep on edits and on large sheets. If you skip it, still write the hard-recalc path and the recalculation order logic so the upgrade is contained.

Can I use a real spreadsheet library instead of building the engine?

For reading and writing .xlsx, yes—libraries exist for most languages and save months on format work. The calculation engine is where libraries vary; check whether the one you're considering recalculates on its own or requires you to supply a formula evaluator. Whatever you choose, the semantics decisions above stay yours to specify.

What's the minimum test set before a first release?

The copy/paste rewriting matrix, a recalculation suite with chained and dense-range dependencies, the error propagation matrix, undo round-trips, and a CSV/XLSX import round-trip. Run each as a full-workbook comparison, not spot checks on single cells.

How do arrays and ranges complicate the dependency model?

A formula that returns a range means dependents of the output region depend on the formula cell, not just on the range's individual source cells. If you support arrays, model output regions explicitly as graph nodes; otherwise, every spilled-result edit produces stale downstream values in ways that are hard to reproduce.