Skip to content
Mog is in active development. The GitHub repo, SDK packages, and community channels are not yet available. Follow for launch updates

Note: SDK packages will be published at launch. This tutorial previews the API.

Use Mog from Python

The Mog Python SDK wraps the Rust compute engine via PyO3, giving you native-speed formula evaluation and XLSX I/O from Python. This tutorial covers workbook creation, formula evaluation, pandas integration, and report generation.

intermediate~20 min

Prerequisites

  • Python 3.9+
  • pandas (optional, for DataFrame conversion)

Install the SDK from PyPI:

bash
pip install mog-sdk

1Create a workbook and set values

Create an in-memory workbook, access the default sheet, and populate cells with data.

python
import mog

wb = mog.create_workbook()
ws = wb.active_sheet()

# Set headers
ws.set_cell("A1", "Product")
ws.set_cell("B1", "Q1")
ws.set_cell("C1", "Q2")
ws.set_cell("D1", "Total")

# Set data rows
products = [
    ("Widget A", 12000, 15000),
    ("Widget B", 8500, 9200),
    ("Widget C", 22000, 24500),
]

for i, (name, q1, q2) in enumerate(products, start=2):
    ws.set_cell(f"A{i}", name)
    ws.set_cell(f"B{i}", q1)
    ws.set_cell(f"C{i}", q2)

print(f"Populated {len(products)} rows")

2Use Excel formulas from Python

Add formulas exactly as you would in Excel. The Rust engine evaluates 500+ functions natively.

python
# Add per-row totals
for i in range(2, 5):
    ws.set_cell(f"D{i}", f"=B{i}+C{i}")

# Add column totals
ws.set_cell("A5", "Total")
ws.set_cell("B5", "=SUM(B2:B4)")
ws.set_cell("C5", "=SUM(C2:C4)")
ws.set_cell("D5", "=SUM(D2:D4)")

# Add an average row
ws.set_cell("A6", "Average")
ws.set_cell("B6", "=AVERAGE(B2:B4)")
ws.set_cell("C6", "=AVERAGE(C2:C4)")
ws.set_cell("D6", "=AVERAGE(D2:D4)")

# Recalculate the workbook
wb.calculate()

# Read computed values
total = ws.get_value("D5")
avg = ws.get_value("D6")
print(f"Grand total: {total}")   # 91200
print(f"Average: {avg}")         # 30400.0

3Convert between Mog and pandas DataFrames

The SDK provides helpers to move data between Mog worksheets and pandas DataFrames in both directions.

python
import pandas as pd

# Worksheet -> DataFrame
df = ws.to_dataframe(header_row=1)
print(df)
#    Product      Q1      Q2    Total
# 0  Widget A  12000   15000    27000
# 1  Widget B   8500    9200    17700
# 2  Widget C  22000   24500    46500
# 3     Total  42500   48700    91200
# 4   Average  14166.7 16233.3  30400.0

# Filter with pandas, then write back to a new sheet
top = df[df["Total"] > 20000].reset_index(drop=True)

ws2 = wb.add_sheet("Top Products")
ws2.from_dataframe(top, start_cell="A1", include_header=True)

print(f"Wrote {len(top)} rows to 'Top Products' sheet")

4Generate reports programmatically

Combine everything into a script that reads raw data, processes it, and writes a formatted XLSX report.

python
import mog

def generate_report(data: list[dict], output_path: str):
    wb = mog.create_workbook()
    ws = wb.active_sheet()
    ws.name = "Report"

    # Write headers
    headers = list(data[0].keys())
    for col, header in enumerate(headers):
        ws.set_cell_by_index(0, col, header)

    # Write data rows
    for row_idx, row_data in enumerate(data, start=1):
        for col_idx, key in enumerate(headers):
            ws.set_cell_by_index(row_idx, col_idx, row_data[key])

    # Add summary formulas
    last_row = len(data) + 1
    ws.set_cell(f"A{last_row + 1}", "TOTAL")
    for col_idx in range(1, len(headers)):
        col_letter = chr(65 + col_idx)
        ws.set_cell(
            f"{col_letter}{last_row + 1}",
            f"=SUM({col_letter}2:{col_letter}{last_row})"
        )

    # Style the header row
    ws.set_row_style(0, bold=True, background="#1e293b", color="#f8fafc")

    wb.calculate()
    wb.save(output_path)
    print(f"Report saved to {output_path}")

# Example usage
sales = [
    {"Region": "North", "Revenue": 120000, "Costs": 85000},
    {"Region": "South", "Revenue": 95000, "Costs": 72000},
    {"Region": "East", "Revenue": 140000, "Costs": 98000},
    {"Region": "West", "Revenue": 110000, "Costs": 79000},
]

generate_report(sales, "sales-report.xlsx")

Next steps