Python Examples

Basic functions

basic.py
import xllify

@xllify.fn("xllipy.Hello")
def hello(name: str) -> str:
    return f"Hello, {name}!"

@xllify.fn("xllipy.Add")
def add(a: float, b: float) -> float:
    return a + b

Slow operations

All Python functions run asynchronously, so slow operations don't freeze Excel:

slow.py
@xllify.fn("xllipy.SlowCalc")
def slow_calc(seconds: float) -> str:
    import time
    time.sleep(seconds)
    return f"Done after {seconds}s"

Excel shows #N/A while waiting, then updates when complete. Note that naively putting a sleep in a function WILL block the execution of other functions. It is best to spawn multiple processes. asyncio support is planned.

Working with ranges

ranges.py
@xllify.fn("xllipy.MaxInRange")
def max_in_range(data: list) -> float:
    max_val = float('-inf')
    for row in data:
        for cell in row:
            if isinstance(cell, (int, float)):
                max_val = max(max_val, cell)
    return max_val

Usage: =xllipy.MaxInRange(A1:Z100)

Black-Scholes option pricing

black_scholes.py
from math import log, sqrt, exp, erf

@xllify.fn("xllipy.BSCall", category="Finance")
def black_scholes_call(s: float, k: float, t: float, r: float, sigma: float) -> float:
    """Black-Scholes call option price"""
    if t <= 0:
        return max(s - k, 0)

    d1 = (log(s / k) + (r + 0.5 * sigma ** 2) * t) / (sigma * sqrt(t))
    d2 = d1 - sigma * sqrt(t)

    def norm_cdf(x):
        return 0.5 * (1 + erf(x / sqrt(2)))

    return s * norm_cdf(d1) - k * exp(-r * t) * norm_cdf(d2)

Usage: =xllipy.BSCall(100, 95, 0.25, 0.05, 0.2)

HTTP requests

http.py
@xllify.fn("xllipy.FetchPrice")
def fetch_price(symbol: str) -> float:
    import requests
    resp = requests.get(f"https://api.example.com/price/{symbol}")
    return resp.json()["price"]

Error handling

errors.py
@xllify.fn("xllipy.SafeDivide")
def safe_divide(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

System info

sysinfo.py
@xllify.fn("xllipy.GetInfo")
def get_info() -> str:
    import sys
    import platform
    return f"Python {sys.version.split()[0]} on {platform.system()}"

Pandas integration

pandas.py
import pandas as pd

@xllify.fn("xllipy.AnalyzeData")
def analyze_data(data: list) -> str:
    df = pd.DataFrame(data[1:], columns=data[0])  # First row is headers
    return f"Mean: {df['value'].mean():.2f}"

Last updated