# Spreadsheet

> A spreadsheet like Google Sheets or Excel: formulas, formats, filters and .xlsx files. A Pyzed component for Python desktop GUIs, with examples and its API.

Source: https://albakore.github.io/pyzed/library/spreadsheet/

:::tip[In plain words]
A grid like Excel where you type numbers and formulas, and the totals update by themselves.
:::

A complete spreadsheet: a grid of cells with formulas (146 functions), number formats, conditional formatting, dropdowns and checkboxes, sorting and filters, frozen panes, merged cells, several sheets, undo, autofill and copy and paste with Sheets and Excel, plus a toolbar, menus and sheet tabs. The data lives in a `pz.Workbook`, which your code reads and writes (`book["B2"]`, `book.records()`) and which opens and saves `.xlsx` and CSV files. It has its own section: [Spreadsheet](https://albakore.github.io/pyzed/spreadsheet/).

`ui.Spreadsheet` · Category: [Data](https://albakore.github.io/pyzed/library/#data) · [Full reference →](https://albakore.github.io/pyzed/reference/spreadsheet/#spreadsheet)

**Code:**

```python
book = pz.Workbook()
book.write([["Item", "Units", "Price", "Total"],
            ["Apples", 120, 0.5, "=B2*C2"],
            ["Pears", 80, 0.75, "=B3*C3"],
            ["Plums", 45, 1.2, "=B4*C4"]])
book["A5"], book["D5"] = "Total", "=SUM(D2:D4)"
book.format("A1:D1", bold=True, fill="#e8f0fe")
book.format("C2:D5", number_format="$#,##0.00")
book.format("A5:D5", bold=True)
book.select("D5")
pz.container(ui.Spreadsheet(book=book), width=760, height=360)
```

:::note[New]
This component was added recently. Tell us how it works for you in the [issue tracker](https://github.com/albakore/pyzed/issues).
:::

## When to use

- When users enter, calculate or review tabular data: budgets, inventories, grades, price lists, imports.
- To show records that are only read and sorted, a [Table](https://albakore.github.io/pyzed/library/table/) is simpler.

## Usage

```python
import pyzed as pz
from pyzed import ui

class Budget(pz.App):
    def __init__(self):
        self.book = pz.Workbook()
        self.book.write([["Item", "Cost"], ["Rent", 950], ["Food", 320]])
        self.book["B4"] = "=SUM(B2:B3)"

    def changed(self, event):
        print(event.value.action, event.value.range, self.book["B4"])

    def view(self):
        return ui.Spreadsheet(book=self.book, on_change=self.changed)
```

## Examples

### Just the grid

Without the toolbar and the tabs it is an editable table with formulas.

**Code:**

```python
book = pz.Workbook.from_rows([
    {"Student": "Ada", "Exam 1": 9, "Exam 2": 8.5},
    {"Student": "Alan", "Exam 1": 7, "Exam 2": 9},
])
book["D1"], book["D2"], book["D3"] = "Average", "=AVERAGE(B2:C2)", "=AVERAGE(B3:C3)"
pz.container(ui.Spreadsheet(book=book, toolbar=False, tabs=False), width=520, height=160)
```

## Events

Spreadsheet has **8 events of its own**, listed below. Like every widget it also has the **18 common events** (`click`, `double_click`, `right_click`, `mouse_enter`, `drag`, `key_down`, `resize`…), attached with `.on(...)`: see [Events](https://albakore.github.io/pyzed/guides/events/) and [Events of every component](https://albakore.github.io/pyzed/library/events/).

It is a `pz.Component`, so it also raises `on_mount` and `on_unmount`, and its handlers get a `pz.Event` whose `value` holds the data.

| Event | Of | Handler gets | When |
| --- | --- | --- | --- |
| `on_change` | `ui.Spreadsheet`, `pz.sheet` | `(event)` | Receives `event.value` with `action`, `range` and `sheet` when the user changes something. |
| `on_select` | `ui.Spreadsheet`, `pz.sheet` | `(event)` | Receives `event.value` with `range` and `sheet` when the selection changes. |
| `on_context` | `pz.sheet` | `(data)` | Called on a right click with `kind` (`"cell"`, `"row"` or `"column"`), `cell`, `x` and `y` (relative to the grid): show a menu there. |
| `on_dropdown` | `pz.sheet` | `(data)` | Called when a list cell's dropdown should open: `cell`, `options`, `x`, `y`, `width`. |
| `on_filter` | `pz.sheet` | `(data)` | Called when a filter button of the header is clicked: `column`, `x`, `y`. |
| `on_find` | `pz.sheet` | `(data)` | Called on Ctrl+F or Ctrl+H: `mode` (`"find"` or `"replace"`). |
| `on_invalid` | `pz.sheet` | `(data)` | Called when a typed value breaks a strict validation rule: `cell`, `value`, `message`. |
| `on_edit` | `pz.sheet` | `(data)` | Called when typing in a cell starts or ends: `editing`. |

**Handler gets** is what Pyzed passes to your callable: `()` means nothing. Any handler can also be a message (a value that is not callable), which goes to `update()`.

### Handling the events

The same events written three ways. **Imperative**: methods of the app change `self`. **Declarative**: the handlers produce messages and one `update()` decides. **Functional**: a pure function draws an immutable state and asks for changes with `set_state(...)`. See [Imperative, declarative and functional](https://albakore.github.io/pyzed/guides/code-styles/).

**Imperative:**

```python
class Budget(pz.App):
    def __init__(self):
        self.book = pz.Workbook()
        self.book.write([["Item", "Cost"], ["Rent", 950], ["Food", 320]])
        self.book["B4"] = "=SUM(B2:B3)"
        self.total = self.book["B4"]

    def changed(self, event):            # on_change: event.value has action, range and sheet
        self.total = self.book["B4"]

    def view(self):
        return pz.column([
            ui.label(f"Total: {self.total}"),
            ui.Spreadsheet(book=self.book, toolbar=False, on_change=self.changed),
        ], spacing=8)
```

**Declarative:**

```python
from dataclasses import dataclass

@dataclass
class Edited:
    range: str

class Budget(pz.App):
    def __init__(self):
        self.book = pz.Workbook()
        self.book.write([["Item", "Cost"], ["Rent", 950], ["Food", 320]])
        self.last = ""

    def update(self, message):
        match message:
            case Edited(range):
                self.last = range

    def view(self):
        return pz.column([
            ui.label(f"Last change: {self.last}"),
            ui.Spreadsheet(book=self.book, tabs=False, on_change=lambda e: Edited(e.value.range)),
        ], spacing=8)
```

**Functional:**

```python
from dataclasses import dataclass

BOOK = pz.Workbook()                     # the data lives in the workbook, not in the state
BOOK.write([["Item", "Cost"], ["Rent", 950], ["Food", 320]])

@dataclass(frozen=True)
class State:
    selection: str = "A1"

def view(state, set_state):
    return pz.column([
        ui.label(f"Selected: {state.selection}"),
        ui.Spreadsheet(book=BOOK, toolbar=False, on_select=lambda e: set_state(selection=e.value.range)),
    ], spacing=8)
```

## Tips

:::tip
Keep the workbook in your app (`self.book`): a `pz.Workbook()` made inside `view()` would start empty on every rebuild.
:::

## Properties and API

### `ui.Spreadsheet`

```python
class Spreadsheet
```

A component: the whole spreadsheet, with the grid and its formula bar, a toolbar, right-click menus, a find bar, panels for conditional formatting, validation and notes, sheet tabs and a status bar with the selection's sum. Everything the user does goes to `book`. See [The Spreadsheet component](https://albakore.github.io/pyzed/spreadsheet/component/).

| Property | Default | Description |
| --- | --- | --- |
| `book` | `None` | The `pz.Workbook` to show and edit (a new empty one when `None`). Keep it in your app so its data survives view rebuilds. |
| `toolbar` | `True` | Shows the toolbar. |
| `formula_bar` | `True` | Shows the name box and the formula bar. |
| `tabs` | `True` | Shows the sheet tabs and the status bar. |
| `headers` | `True` | Shows the column letters and row numbers. |
| `readonly` | `False` | Users can select, copy and find, but not change anything. |
| `text_size` | `13` | Pixel size of 10 pt text. |
| `width` | `"fill"` | Width: pixels, `"fill"`, `"shrink"` or `"fill:N"` (proportion). |
| `height` | `"fill"` | Height: pixels, `"fill"`, `"shrink"` or `"fill:N"` (proportion). |

Events: `on_change`, `on_select` ([events](#events)).

[Full reference →](https://albakore.github.io/pyzed/reference/spreadsheet/#spreadsheet)

### `pz.Workbook`

```python
class Workbook
```

A spreadsheet workbook: sheets of cells with values, formulas and formats.

[Full reference →](https://albakore.github.io/pyzed/reference/spreadsheet/#workbook-1)

### `pz.sheet`

```python
sheet(
    book,
    *,
    colors=None,
    text_size=13.0,
    formula_bar=True,
    headers=True,
    width=None,
    height=None,
    readonly=False,
    on_change=None,
    on_select=None,
    on_context=None,
    on_dropdown=None,
    on_filter=None,
    on_find=None,
    on_invalid=None,
    on_edit=None,
)
```

The spreadsheet grid on its own: cells, headers and formula bar, with selection, editing, formulas, the fill handle, copy and paste and the keyboard shortcuts of Sheets and Excel. It draws only the cells in view. The grid doesn't draw menus: its events say where the user clicked. See [The grid on its own](https://albakore.github.io/pyzed/spreadsheet/grid/).

| Property | Default | Description |
| --- | --- | --- |
| `book` | *required* | The `pz.Workbook` to show. |
| `colors` | `None` | A dict of colors (`background`, `grid`, `header`, `text`, `accent`, `selection`...); `ui.sheet_colors(theme)` makes one from a theme. |
| `text_size` | `13.0` | Pixel size of 10 pt text. |
| `formula_bar` | `True` | Shows the name box and the formula bar. |
| `headers` | `True` | Shows the column letters and row numbers. |
| `width` | `None` | Width: pixels, `"fill"`, `"shrink"` or `"fill:N"` (proportion). |
| `height` | `None` | Height: pixels, `"fill"`, `"shrink"` or `"fill:N"` (proportion). |
| `readonly` | `False` | Select and copy only. |

Events: `on_change`, `on_select`, `on_context`, `on_dropdown`, `on_filter`, `on_find`, `on_invalid`, `on_edit` ([events](#events)).

[Full reference →](https://albakore.github.io/pyzed/reference/spreadsheet/#sheet)

### `ui.sheet_colors`

```python
sheet_colors(theme=None)
```

The colors `ui.Spreadsheet` gives its grid for a theme, as the dict `pz.sheet(colors=...)` takes.

| Property | Default | Description |
| --- | --- | --- |
| `theme` | `None` | A theme (the current one by default). |

[Full reference →](https://albakore.github.io/pyzed/reference/spreadsheet/#sheet_colors)

## Related

- [Table](https://albakore.github.io/pyzed/library/table/): A data table with a fixed header, sorting and selection.
- [Virtual list](https://albakore.github.io/pyzed/library/virtual-list/): A list that only builds the rows in view, for millions of items.
- [Line chart](https://albakore.github.io/pyzed/library/line-chart/): Lines with axes, labels and a legend.
