Skip to content
Mog is in active development. The GitHub repo, SDK packages, and community channels are not yet available. Follow for launch updates
Mog is pre-launch. These examples show the planned API surface and may change before the first stable release.

Examples

Copy-paste recipes for common tasks

Embedding

Drop a live spreadsheet into any web application with the Mog embed SDK.

Basic embed

Render an interactive spreadsheet inside a React component. The MogSheet component handles WASM loading and canvas rendering automatically.

// tsx
import { MogSheet } from "@mog-sdk/embed/react";

export default function SpreadsheetPage() {
  return (
    <MogSheet
      width={1200}
      height={600}
      initialData={{
        A1: "Product",
        B1: "Q1",
        C1: "Q2",
        A2: "Widget",
        B2: 12000,
        C2: 15000,
        A3: "Gadget",
        B3: 8500,
        C3: 9200,
        A4: "Total",
        B4: "=SUM(B2:B3)",
        C4: "=SUM(C2:C3)",
      }}
    />
  );
}

Load from URL

Fetch and display a remote XLSX file. Mog downloads the file, parses it client-side in WASM, and renders the result on canvas.

// tsx
import { MogSheet } from "@mog-sdk/embed/react";

export default function RemoteFile() {
  return (
    <MogSheet
      src="https://example.com/reports/sales-q1.xlsx"
      width={1200}
      height={600}
      onLoad={(workbook) => {
        console.log("Loaded sheets:", workbook.getSheetNames());
      }}
      onError={(err) => {
        console.error("Failed to load:", err);
      }}
    />
  );
}

Controlled mode

Access the workbook instance programmatically after embed. Read and write cells, listen for changes, and drive the sheet from external UI.

// tsx
import { useRef, useCallback } from "react";
import { MogSheet, type MogWorkbook } from "@mog-sdk/embed/react";

export default function ControlledSheet() {
  const wbRef = useRef<MogWorkbook>(null);

  const handleLoad = useCallback((wb: MogWorkbook) => {
    wbRef.current = wb;
  }, []);

  const readTotal = useCallback(async () => {
    const wb = wbRef.current;
    if (!wb) return;
    const sheet = wb.getActiveSheet();
    const value = await sheet.getValue("C10");
    alert(`Total: ${value}`);
  }, []);

  return (
    <div>
      <button onClick={readTotal}>Read C10</button>
      <MogSheet
        src="/data/budget.xlsx"
        width={1200}
        height={600}
        onLoad={handleLoad}
      />
    </div>
  );
}

Server-Side

Use the Node.js SDK to read, generate, and convert spreadsheets on the server.

Read XLSX

Open an Excel file and iterate over every cell. Mog parses OOXML natively in Rust, exposed via N-API bindings to Node.js.

// typescript
import { openWorkbook } from "@mog-sdk/node";

const wb = await openWorkbook("input.xlsx");
const sheet = wb.getSheet("Sheet1");
const range = sheet.getUsedRange();

for (let row = range.startRow; row <= range.endRow; row++) {
  for (let col = range.startCol; col <= range.endCol; col++) {
    const cell = sheet.getCell(row, col);
    console.log(`[${cell.address}] ${cell.value} (type: ${cell.type})`);
  }
}

Generate report

Create a workbook from scratch, populate it with data and formulas, then export to XLSX. Useful for automated report pipelines.

// typescript
import { createWorkbook, save } from "@mog-sdk/node";

const wb = await createWorkbook();
const ws = wb.getActiveSheet();

// Header row
const headers = ["Month", "Revenue", "Expenses", "Profit"];
headers.forEach((h, i) => ws.setCell(0, i, h));

// Data rows
const data = [
  ["Jan", 52000, 34000],
  ["Feb", 61000, 37000],
  ["Mar", 58000, 35500],
];
data.forEach((row, r) => {
  row.forEach((val, c) => ws.setCell(r + 1, c, val));
  ws.setCell(r + 1, 3, `=B${r + 2}-C${r + 2}`);
});

// Summary row
const lastRow = data.length + 1;
ws.setCell(lastRow, 0, "Total");
ws.setCell(lastRow, 1, `=SUM(B2:B${lastRow})`);
ws.setCell(lastRow, 2, `=SUM(C2:C${lastRow})`);
ws.setCell(lastRow, 3, `=SUM(D2:D${lastRow})`);

await wb.calculate();
await save(wb, "quarterly-report.xlsx");

Batch convert

Process every XLSX file in a directory: parse it, extract a summary row, and write results to a new consolidated workbook.

// typescript
import { readdir } from "node:fs/promises";
import { join } from "node:path";
import { openWorkbook, createWorkbook, save } from "@mog-sdk/node";

const inputDir = "./reports";
const files = (await readdir(inputDir)).filter((f) => f.endsWith(".xlsx"));

const summary = await createWorkbook();
const out = summary.getActiveSheet();
out.setCell(0, 0, "File");
out.setCell(0, 1, "Rows");
out.setCell(0, 2, "Total (A column sum)");

for (let i = 0; i < files.length; i++) {
  const wb = await openWorkbook(join(inputDir, files[i]));
  const sheet = wb.getSheet(0);
  const range = sheet.getUsedRange();
  const rowCount = range.endRow - range.startRow + 1;

  // Sum the first numeric column
  sheet.setCell(range.endRow + 1, 0, `=SUM(A1:A${range.endRow + 1})`);
  await wb.calculate();
  const colSum = sheet.getValue(range.endRow + 1, 0);

  out.setCell(i + 1, 0, files[i]);
  out.setCell(i + 1, 1, rowCount);
  out.setCell(i + 1, 2, colSum);
}

await save(summary, "consolidated-summary.xlsx");
console.log(`Processed ${files.length} files.`);

Formulas

Mog supports 500+ Excel-compatible functions. These recipes show common formula patterns.

Financial model

Build a simple investment analysis with NPV, IRR, and PMT. All financial functions follow Excel semantics exactly.

// typescript
import { createWorkbook, save } from "@mog-sdk/node";

const wb = await createWorkbook();
const ws = wb.getActiveSheet();

// Assumptions
ws.setCell("A1", "Discount Rate");   ws.setCell("B1", 0.08);
ws.setCell("A2", "Initial Outlay");  ws.setCell("B2", -500000);
ws.setCell("A3", "Year 1 CF");       ws.setCell("B3", 120000);
ws.setCell("A4", "Year 2 CF");       ws.setCell("B4", 150000);
ws.setCell("A5", "Year 3 CF");       ws.setCell("B5", 180000);
ws.setCell("A6", "Year 4 CF");       ws.setCell("B6", 200000);

// Analysis
ws.setCell("A8", "NPV");
ws.setCell("B8", "=NPV(B1, B3:B6) + B2");

ws.setCell("A9", "IRR");
ws.setCell("B9", "=IRR(B2:B6)");

ws.setCell("A11", "Equivalent loan payment (5yr, 6%)");
ws.setCell("B11", "=PMT(0.06/12, 60, B2)");

await wb.calculate();
console.log("NPV:", ws.getValue("B8"));
console.log("IRR:", ws.getValue("B9"));
console.log("Monthly PMT:", ws.getValue("B11"));

await save(wb, "financial-model.xlsx");

Data validation

Use COUNTIF, SUMIFS, and conditional logic to validate and summarize data. These patterns are common in data cleaning workflows.

// typescript
import { createWorkbook } from "@mog-sdk/node";

const wb = await createWorkbook();
const ws = wb.getActiveSheet();

// Sample dataset
ws.setCell("A1", "Region"); ws.setCell("B1", "Status"); ws.setCell("C1", "Amount");
ws.setCell("A2", "North");  ws.setCell("B2", "Closed"); ws.setCell("C2", 4500);
ws.setCell("A3", "South");  ws.setCell("B3", "Open");   ws.setCell("C3", 3200);
ws.setCell("A4", "North");  ws.setCell("B4", "Closed"); ws.setCell("C4", 6100);
ws.setCell("A5", "East");   ws.setCell("B5", "Open");   ws.setCell("C5", 2800);
ws.setCell("A6", "North");  ws.setCell("B6", "Closed"); ws.setCell("C6", 5300);

// Validation & summary formulas
ws.setCell("E1", "Closed deals (North)");
ws.setCell("F1", '=COUNTIFS(A2:A6, "North", B2:B6, "Closed")');

ws.setCell("E2", "Revenue (North, Closed)");
ws.setCell("F2", '=SUMIFS(C2:C6, A2:A6, "North", B2:B6, "Closed")');

ws.setCell("E3", "Has open deals?");
ws.setCell("F3", '=IF(COUNTIF(B2:B6, "Open") > 0, "Yes", "No")');

ws.setCell("E4", "Largest deal");
ws.setCell("F4", "=MAX(C2:C6)");

await wb.calculate();
console.log("Closed deals (North):", ws.getValue("F1"));
console.log("Revenue:", ws.getValue("F2"));
console.log("Has open deals?:", ws.getValue("F3"));
console.log("Largest deal:", ws.getValue("F4"));

Lookup tables

Use VLOOKUP and INDEX/MATCH to cross-reference data between tables. INDEX/MATCH is more flexible and handles left-lookups.

// typescript
import { createWorkbook } from "@mog-sdk/node";

const wb = await createWorkbook();
const ws = wb.getActiveSheet();

// Product lookup table
ws.setCell("A1", "SKU");    ws.setCell("B1", "Name");     ws.setCell("C1", "Price");
ws.setCell("A2", "WDG-01"); ws.setCell("B2", "Widget A"); ws.setCell("C2", 29.99);
ws.setCell("A3", "WDG-02"); ws.setCell("B3", "Widget B"); ws.setCell("C3", 49.99);
ws.setCell("A4", "GDG-01"); ws.setCell("B4", "Gadget X"); ws.setCell("C4", 89.99);
ws.setCell("A5", "GDG-02"); ws.setCell("B5", "Gadget Y"); ws.setCell("C5", 119.99);

// VLOOKUP — find price by SKU
ws.setCell("E1", "Lookup SKU");
ws.setCell("F1", "WDG-02");
ws.setCell("E2", "VLOOKUP Price");
ws.setCell("F2", '=VLOOKUP(F1, A2:C5, 3, FALSE)');

// INDEX/MATCH — find SKU by name (left-lookup)
ws.setCell("E4", "Lookup Name");
ws.setCell("F4", "Gadget X");
ws.setCell("E5", "INDEX/MATCH SKU");
ws.setCell("F5", '=INDEX(A2:A5, MATCH(F4, B2:B5, 0))');

// Two-way lookup with INDEX/MATCH
ws.setCell("E7", "Match Result");
ws.setCell("F7", '=INDEX(C2:C5, MATCH("GDG-02", A2:A5, 0))');

await wb.calculate();
console.log("VLOOKUP price:", ws.getValue("F2"));
console.log("INDEX/MATCH SKU:", ws.getValue("F5"));
console.log("Two-way lookup:", ws.getValue("F7"));

Python

Use the Python SDK (via PyO3) to bridge pandas, NumPy, and Mog.

DataFrame to spreadsheet

Convert a pandas DataFrame into a Mog workbook and export to XLSX. Column headers and dtypes are preserved automatically.

# python
import pandas as pd
from mog import Workbook

df = pd.DataFrame({
    "Product": ["Widget", "Gadget", "Doohickey"],
    "Units Sold": [1200, 850, 2100],
    "Unit Price": [29.99, 49.99, 9.99],
    "Revenue": [35988.0, 42491.5, 20979.0],
})

wb = Workbook()
ws = wb.active_sheet()

# Write headers
for col, name in enumerate(df.columns):
    ws.set_cell(0, col, name)

# Write data
for row_idx, row in df.iterrows():
    for col_idx, value in enumerate(row):
        ws.set_cell(row_idx + 1, col_idx, value)

# Add a total row with formulas
total_row = len(df) + 1
ws.set_cell(total_row, 0, "Total")
ws.set_cell(total_row, 1, f"=SUM(B2:B{total_row})")
ws.set_cell(total_row, 3, f"=SUM(D2:D{total_row})")

wb.calculate()
wb.save("products.xlsx")
print(f"Saved {len(df)} rows + summary to products.xlsx")

Formula evaluation

Use Mog as a formula engine from Python. Set up cells, evaluate formulas, and read back results without any file I/O.

# python
from mog import Workbook

wb = Workbook()
ws = wb.active_sheet()

# Build a small model
ws.set_cell("A1", 100)     # principal
ws.set_cell("A2", 0.05)    # annual rate
ws.set_cell("A3", 12)      # months

# Compound interest formula
ws.set_cell("B1", "=A1 * (1 + A2/12) ^ A3")

# Statistical functions
data = [23, 45, 67, 12, 89, 34, 56]
for i, v in enumerate(data):
    ws.set_cell(i, 3, v)  # column D

ws.set_cell("E1", f"=AVERAGE(D1:D{len(data)})")
ws.set_cell("E2", f"=STDEV(D1:D{len(data)})")
ws.set_cell("E3", f"=MEDIAN(D1:D{len(data)})")

wb.calculate()

print("Compound interest:", ws.get_value("B1"))
print("Average:", ws.get_value("E1"))
print("Std dev:", ws.get_value("E2"))
print("Median:", ws.get_value("E3"))

Report generation

Create a formatted Excel report with multiple sheets, styled headers, and summary formulas. Useful for automated reporting pipelines.

# python
from mog import Workbook
from datetime import date

wb = Workbook()

# --- Data sheet ---
data_ws = wb.active_sheet()
data_ws.set_name("Sales Data")

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
regions = ["North", "South", "East", "West"]

# Headers
data_ws.set_cell(0, 0, "Month")
for j, region in enumerate(regions):
    data_ws.set_cell(0, j + 1, region)

# Sample data (in practice, pull from a database)
import random
random.seed(42)
for i, month in enumerate(months):
    data_ws.set_cell(i + 1, 0, month)
    for j in range(len(regions)):
        data_ws.set_cell(i + 1, j + 1, random.randint(10000, 50000))

# --- Summary sheet ---
summary_ws = wb.add_sheet("Summary")
summary_ws.set_cell("A1", "Region")
summary_ws.set_cell("B1", "Total Sales")
summary_ws.set_cell("C1", "Average")

for j, region in enumerate(regions):
    col_letter = chr(ord("B") + j)
    summary_ws.set_cell(j + 1, 0, region)
    summary_ws.set_cell(j + 1, 1,
        f"=SUM('Sales Data'!{col_letter}2:{col_letter}7)")
    summary_ws.set_cell(j + 1, 2,
        f"=AVERAGE('Sales Data'!{col_letter}2:{col_letter}7)")

summary_ws.set_cell("A6", f"Report generated: {date.today()}")

wb.calculate()
wb.save("monthly-sales-report.xlsx")
print("Report saved with 2 sheets.")

More examples

Looking for deeper walkthroughs or more advanced patterns?