sheet

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package sheet is the spreadsheet engine: cell storage, formula parsing and dependency-ordered recalculation. It has no knowledge of the terminal UI.

Index

Constants

View Source
const (
	MinChartW, MinChartH = 20, 8
	MaxChartW, MaxChartH = 240, 120
)

Chart size limits, in terminal cells.

View Source
const (
	MaxCols = formula.MaxCols
	MaxRows = formula.MaxRows
)

Worksheet bounds, matching Lotus 1-2-3 Release 2 (A..IV, 1..8192).

View Source
const (
	Empty  = value.Empty
	Number = value.Number
	Text   = value.Text
	Bool   = value.Bool
	Error  = value.Error
)

Kinds of values.

View Source
const (
	FmtAuto       = value.FmtAuto
	FmtText       = value.FmtText
	FmtNumber     = value.FmtNumber
	FmtPercent    = value.FmtPercent
	FmtScientific = value.FmtScientific
	FmtAccounting = value.FmtAccounting
	FmtFinancial  = value.FmtFinancial
	FmtCurrency   = value.FmtCurrency
	FmtDate       = value.FmtDate
	FmtTime       = value.FmtTime
	FmtDateTime   = value.FmtDateTime
	FmtDuration   = value.FmtDuration
	FmtCustom     = value.FmtCustom

	// MaxDecimals caps Increase decimal places.
	MaxDecimals = value.MaxDecimals
)

Number formats.

View Source
const DefaultMaxCells = 2_000_000

DefaultMaxCells is the max-cells setting's default: about 600 MB of cells at 300 bytes each.

View Source
const DefaultWidth = 10

DefaultWidth is the initial column width: nine characters plus padding.

View Source
const FileExt = ".012"

FileExt is the extension of the native worksheet format.

View Source
const MacroAPI = 1

MacroAPI is the version of the scripting API macros are written for. A file records it with each macro, so a later build that changes the API can tell old scripts from new ones.

View Source
const MaxFrozen = 50

MaxFrozen caps frozen rows and columns, as Sheets' View > Freeze does in practice: more than a screenful can't stay on screen anyway.

View Source
const MaxUndo = 100

MaxUndo is how many steps of undo history a workbook keeps, at most; MaxUndoBytes also bounds it.

View Source
const MaxUndoBytes = 256 << 20

MaxUndoBytes caps the memory the undo history's before-images hold, as estimated by step.size. When a new step takes the history past it, the oldest steps are dropped first; the newest step is always kept, however large, so any single change can be undone. 256 MB keeps MaxUndo steps that each rewrite a whole column (about 250 MB, see docs/limits.md).

Variables

View Source
var (
	// OnBegin, when set, is called as a recalculation ("recalc") or a
	// pivot table refresh ("pivot") begins; OnRecalc or OnPivot as it
	// ends. They pair up like parentheses: a recalculation holds the
	// pivot refreshes it causes, which follow its own evaluation.
	OnBegin func(trace any, op string)
	// OnRecalc, when set, is called after every recalculation of any
	// workbook.
	OnRecalc func(trace any, i RecalcInfo)
)

The engine knows nothing of logging; cmd/012 points these hooks at telemetry. They run on the goroutine that changed the workbook and must be cheap. trace is the workbook's (see SetTrace), handed back so the engine's work is timed as spans nested in whatever the workbook's owner has open: a command, an import, a macro run.

View Source
var (
	ErrPushedOff  = errors.New("There's data at the edge of the sheet that would be pushed off")
	ErrPasteEdge  = errors.New("The paste doesn't fit: it would go past the edge of the sheet")
	ErrFillTooBig = errors.New("That would write more cells than max-cells allows (see File > Settings)")
)

Errors returned by operations that would lose data or don't fit.

View Source
var (
	// Pending is shown while an answer is on its way.
	Pending = functions.Pending
	// ErrNoRemote means JEV functions can't run: there is no API key.
	ErrNoRemote = functions.ErrNoRemote
	// ErrRemote is a question the model couldn't answer.
	ErrRemote = functions.ErrRemote
)
View Source
var (
	ErrDiv0  = value.ErrDiv0
	ErrValue = value.ErrValue
	ErrName  = value.ErrName
	ErrNA    = value.ErrNA
	ErrNum   = value.ErrNum
	ErrRef   = value.ErrRef // also circular references
)

Error values, using Google Sheets codes.

View Source
var ChartTypes = func() []ChartType {
	out := make([]ChartType, len(chartTypeNames))
	for i := range out {
		out[i] = ChartType(i)
	}
	return out
}()

ChartTypes lists the types in the order the chart editor offers them.

View Source
var (
	// ErrPivotEdit is what editing a pivot table's results says, as
	// Sheets refuses to.
	ErrPivotEdit = errors.New("Pivot table results can't be edited: change the pivot with Data > Edit pivot table")
)

Errors of pivot tables.

View Source
var OnPivot func(trace any, i PivotInfo)

OnPivot, when set, is called after every pivot recomputation, like OnRecalc (see OnBegin).

Functions

func ColName

func ColName(c int) string

ColName converts a zero-based column index to letters: 0 -> A, 26 -> AA.

func FormatNumber

func FormatNumber(v float64, width int) string

FormatNumber formats a number in the General format within width columns, for use outside the grid (e.g. the status line).

func FormatPattern

func FormatPattern(v float64, pat string) string

FormatPattern renders v with a number format pattern, as TEXT() does.

func FormatText

func FormatText(v Value, f Format) string

FormatText renders v under f with no width limit, e.g. for TEXT() or copying out of the grid.

func FormatValue

func FormatValue(v Value, width int) string

FormatValue renders v in width columns with one column of padding, the way the grid shows it in Automatic format: numbers right-aligned, booleans and errors centered. Text is not handled here because it can overflow into neighboring cells.

func IsFormulaEntry

func IsFormulaEntry(input string) bool

IsFormulaEntry reports whether input is written as a formula: it starts with "=", or with "+" or "-" followed by something that isn't a plain number (as Sheets accepts "+A1").

func IsPending

func IsPending(v Value) bool

IsPending reports whether v is waiting for a remote answer.

func MaxCells

func MaxCells() int

MaxCells returns the cell budget.

func ParseCol

func ParseCol(s string) (int, bool)

ParseCol converts column letters (case-insensitive) to a zero-based index.

func ParseNumber

func ParseNumber(s string) (float64, bool)

ParseNumber recognizes numbers the way Google Sheets does on entry.

func Qualified

func Qualified(sheet string, r Rect) string

Qualified writes r on sheet as a formula would: Sheet2!A1:B3.

func QuoteSheet

func QuoteSheet(name string) string

QuoteSheet writes a sheet name as a formula needs it, e.g. 'Q3 plan'.

func SetMaxCells

func SetMaxCells(n int)

SetMaxCells sets the cell budget; n < 1 restores the default.

func ShiftEntry

func ShiftEntry(input string, dc, dr int) (string, error)

ShiftEntry returns an entry as if it were typed in one cell and copied dc columns and dr rows away: a formula's relative references move and $absolute ones stay, as in a paste. Other entries come back unchanged. A macro recorded with relative references replays formulas this way.

func SplitSheet

func SplitSheet(s string) (sheet, rest string)

SplitSheet splits a reference such as "'Q3 plan'!B2" into the sheet name, unquoted, and the rest.

func ValidMacroName

func ValidMacroName(name string) error

ValidMacroName reports why name can't name a macro, or nil.

func ValidName

func ValidName(name string) error

ValidName checks that name can be a named range, following Sheets' rules: letters, digits, _ and ., starting with a letter or _, and not something a formula would read as a cell or a boolean.

func ValidSheetName

func ValidSheetName(name string) error

ValidSheetName checks a name for a sheet, following Excel's rules (a superset of what Sheets accepts is fine to read, but names written by 012 must open in Excel too).

Types

type Addr

type Addr = formula.Addr

Addr identifies a cell by zero-based column and row.

func ParseAddr

func ParseAddr(s string) (Addr, bool)

ParseAddr parses an A1-style reference, ignoring absolute markers.

type Align

type Align uint8

Align is a cell's horizontal alignment.

const (
	AlignAuto   Align = iota // numbers right, text left, booleans and errors centered
	AlignLeft                //
	AlignCenter              //
	AlignRight               //
	// AlignFill is only returned by Display: the text spans the cell
	// exactly and isn't padded (Accounting's $ at the left edge).
	AlignFill
)

func Display

func Display(v Value, f Format, width int) (string, Align)

Display renders v under format f for a cell width columns wide, as the grid shows it: the text without padding, and where it goes. Numbers go right, text left, booleans and errors center. A formatted number that doesn't fit in width-1 columns becomes a run of #, as in Sheets; Automatic first drops decimals and falls back to scientific notation. Accounting returns AlignFill: exactly width columns, $ at the left.

func ParseAlign

func ParseAlign(s string) (Align, bool)

ParseAlign is the inverse of Align.String.

func (Align) String

func (a Align) String() string

String returns the alignment's name as stored in files.

type Cell

type Cell struct {
	// Input is the entry exactly as typed: text, a number such as "$1,200"
	// or "12%", or a formula starting with "=". Empty for a blank cell
	// that only has formatting.
	Input string
	Value Value

	// Format and Style are plain values, so copying a Cell copies its
	// formatting. They survive clearing the contents, as in Sheets.
	Format Format
	Style  Style
	// contains filtered or unexported fields
}

Cell holds what the user typed, what it evaluates to, and how it is formatted. A cell may have formatting but no contents (Sheets lets you format blank cells before typing); such a cell counts as blank everywhere contents matter.

func (*Cell) Blank

func (c *Cell) Blank() bool

Blank reports whether the cell has no contents (it may still have formatting).

func (*Cell) IsFormula

func (c *Cell) IsFormula() bool

IsFormula reports whether the cell holds a formula.

type Change

type Change struct {
	Label string
	Focus Rect
	Sheet *Sheet
	// Tabs is set when the step added, deleted, renamed or moved sheets;
	// Focus means nothing then.
	Tabs bool
	// Macros is set when the step changed nothing but the macros; Focus
	// means nothing then either.
	Macros bool
}

Change describes an undo step: what it did, in lower case for use in a sentence ("clear B3:B5"), the sheet it happened on and the range it affected there.

type Chart

type Chart struct {
	Type ChartType
	Data Rect
	// ByRow puts each series in a row instead of a column, like Sheets'
	// "Switch rows / columns".
	ByRow bool
	// Header takes series names from the first row of the data (the first
	// column when ByRow).
	Header bool
	// Labels takes category labels from the first column of the data (the
	// first row when ByRow).
	Labels bool
	Title  string
	At     Addr // the cell under the top-left corner
	W, H   int  // size in terminal cells
}

Chart is a chart floating over the grid.

type ChartData

type ChartData struct {
	Categories []string
	Series     []ChartSeries
	Format     Format
}

ChartData is what a chart draws: category labels and series of the same length, and the number format of the values, for axis labels.

type ChartFate

type ChartFate struct {
	Name     string // the chart's title, or Chart 1, Chart 2 by position
	Was, Now Rect   // the range it drew, and draws
	Empty    bool   // the new data has nothing in Now
}

ChartFate says what replacing a sheet did to one of its charts.

type ChartSeries

type ChartSeries struct {
	Name   string
	Values []float64
}

ChartSeries is one named run of values. Blank and non-numeric cells are NaN, drawn as gaps.

type ChartType

type ChartType int

ChartType is how a chart draws its series. Adding one takes a constant here and its name in chartTypeNames; the chart editor, the file format and ChartTypes follow from the table, and internal/chart draws it.

const (
	ChartColumn ChartType = iota // vertical bars, one group per category
	ChartBar                     // horizontal bars
	ChartLine                    // one line per series
	ChartPie                     // the first series as slices of a whole
)

func ParseChartType

func ParseChartType(s string) (ChartType, bool)

ParseChartType parses a type name as String writes it.

func (ChartType) String

func (t ChartType) String() string

func (ChartType) Title

func (t ChartType) Title() string

Title is the type's name as the chart editor shows it, e.g. "Column".

type Clip

type Clip struct {
	Range Rect // the range copied
	Src   Rect // Range trimmed to its cells when whole lines
	// contains filtered or unexported fields
}

Clip is a copied range: snapshots of its cells, and of the formatting they show, taken at copy time.

func (*Clip) MoveRange

func (c *Clip) MoveRange(to Addr) Rect

MoveRange is the range cutting c moves when pasted at to: the whole lines copied when to starts a line, else the copied cells.

func (*Clip) Size

func (c *Clip) Size() (cols, rows int)

Size returns the clip's width and height in cells.

func (*Clip) Text

func (c *Clip) Text() [][]string

Text returns the clip's values as displayed in General format, row by row, for the system clipboard. Blank rows and columns past the last value are left off, so copying whole columns gives their data; a block of more than MaxCells cells, blanks between values included, is too big for text, and Text returns nil.

type CondOp

type CondOp uint8

CondOp is one of Sheets' filter conditions.

const (
	CondNone CondOp = iota
	CondEmpty
	CondNotEmpty
	CondContains
	CondNotContains
	CondStartsWith
	CondEndsWith
	CondExactly
	CondGreater
	CondGreaterEq
	CondLess
	CondLessEq
	CondEqual
	CondNotEqual
)

func CondOps

func CondOps() []CondOp

CondOps lists the conditions in the order Sheets' menu shows them.

func ParseCondOp

func ParseCondOp(s string) (CondOp, bool)

ParseCondOp is the inverse of CondOp.String.

func (CondOp) String

func (op CondOp) String() string

String names the condition as stored in files.

func (CondOp) TakesArg

func (op CondOp) TakesArg() bool

TakesArg reports whether the condition compares with a value.

func (CondOp) Title

func (op CondOp) Title() string

Title names the condition for people, e.g. "Greater than".

type Condition

type Condition struct {
	Op  CondOp
	Arg string // the value compared with, as typed; unused by CondEmpty and CondNotEmpty
}

Condition is a test on a cell, e.g. "greater than 100".

func (Condition) Matches

func (c Condition) Matches(v Value, shown string) bool

Matches reports whether a cell with value v, shown as shown, meets the condition, as the filter tests it.

type Criteria

type Criteria struct {
	Hidden []string
	Cond   Condition
}

Criteria is what one column of a filter lets through: its displayed value must not be one of Hidden (Sheets' "Filter by values", unchecked values; "" stands for blanks) and must meet Cond ("Filter by condition").

func (Criteria) IsZero

func (c Criteria) IsZero() bool

IsZero reports whether the criteria let every row through.

type Filter

type Filter struct {
	Range Rect
	Cols  map[int]Criteria // by column; a column without criteria hides nothing
}

A filter hides the rows of a range whose values don't meet criteria set per column, as Sheets' Data > Create a filter. Rows are hidden, never deleted: formulas still see them (SUM over a filtered range includes hidden rows, as in Sheets). The range's first row holds the headers and is never hidden. Criteria are re-applied whenever values change.

type FilterValue

type FilterValue struct {
	Text  string // "" for blanks
	Count int
	Shown bool
}

FilterValue is one entry of a filter's values list: a value as shown, how many rows have it, and whether it is checked (shown).

type FindOptions

type FindOptions struct {
	MatchCase  bool
	WholeCell  bool  // the whole cell must match, not just part of it
	Regex      bool  // the query is a regular expression; replacements may use $1
	InFormulas bool  // search formula text instead of formula results
	Within     *Rect // limit the search to a range; nil searches the sheet
}

FindOptions mirror Google Sheets' Find and replace dialog.

type Format

type Format = value.Format

Format is a cell's number format.

func ParseValue

func ParseValue(s string) (float64, Format, bool)

ParseValue recognizes everything Sheets turns into a number on entry: numbers, currency, percentages, dates and times, with the format Sheets applies.

func Preset

func Preset(k FormatKind) Format

Preset returns kind with Sheets' default decimals: two for the number kinds.

type FormatKind

type FormatKind = value.FormatKind

FormatKind is a number format from Sheets' Format > Number menu.

func ParseFormatKind

func ParseFormatKind(s string) (FormatKind, bool)

ParseFormatKind is the inverse of FormatKind.String.

type FuncDef

type FuncDef = functions.FuncDef

FuncDef describes a spreadsheet function.

func Funcs

func Funcs() []*FuncDef

Funcs returns every function, sorted by name.

func LookupFunc

func LookupFunc(name string) (*FuncDef, bool)

LookupFunc finds a function by name or alias; callers pass upper case.

type ImportResult

type ImportResult struct {
	Sheets  []*Sheet          // the sheets added, in tab order
	Renamed map[string]string // imported names changed to fit, old to new
	Names   int               // named ranges left out, their names taken
}

ImportResult says what an import into a workbook did.

type Kind

type Kind = value.Kind

Kind is the type of a computed cell value.

type Macro

type Macro struct {
	Name   string
	Key    string // the shortcut's digit, "0" to "9", or "" for none
	Source string // the Starlark script
	API    int    // the scripting API it was written for, MacroAPI or older
}

Macro is a saved macro.

type Name

type Name struct {
	Name  string // as the user spelled it; formulas match it in any case
	Sheet *Sheet // the sheet the range is on
	Range Rect
	// Lost is set when every cell of the range was deleted: formulas using
	// the name show #REF!, as in Sheets. Range is then zero.
	Lost bool
}

Name is a named range. Names belong to the workbook, as in Sheets, and each points at a range on one of its sheets.

func (Name) Gone

func (n Name) Gone() bool

Gone reports whether the name no longer points at cells: its cells or its sheet were deleted.

func (Name) Ref

func (n Name) Ref() string

Ref is what the name stands for, e.g. "B2:B20", or "#REF!" when gone. In a workbook of several sheets it names the sheet: "Sales!B2:B20".

type Node

type Node = formula.Node

Node is a parsed formula expression.

func Parse

func Parse(src string) (Node, error)

Parse parses a formula with this engine's functions. src may start with "="; error positions are relative to src.

type ParseError

type ParseError = formula.ParseError

ParseError describes a formula that could not be parsed.

type Pivot

type Pivot struct {
	// Source names the sheet the data is on. Like a reference written
	// with a sheet name, it follows renames, and while no sheet has the
	// name the pivot shows #REF!.
	Source string
	// Range is the data on the source sheet; its first row holds the
	// headers, which name the fields.
	Range   Rect
	Rows    []PivotGroup
	Columns []PivotGroup
	Values  []PivotValue
	Filters []PivotFilter
	// RowTotals adds a Grand Total row, and a subtotal row after each
	// outer group when there are several row groups. ColumnTotals adds a
	// Grand Total column when there are column groups.
	RowTotals, ColumnTotals bool
	// Lost is set when the source range was deleted.
	Lost bool
}

A pivot table summarizes a range of another sheet, as Sheets' Insert > Pivot table: rows grouped by the values of some columns (Rows), spread across others (Columns), with values summarized per group (Values), and rows left out by Filters. It lives on a sheet of its own, starting at A1. The engine owns its results: they are derived cells, recomputed whenever the source's cells change, never saved (the file keeps the definition) and never edited by hand. A sheet has at most one pivot.

func FrequencyPivot

func FrequencyPivot(src *Sheet, r Rect, col int) Pivot

FrequencyPivot is a frequency table of column col of r: each distinct value with how many rows have it and their share, most frequent first, as VisiData's Shift+F. It is a pivot like any other; it counts rows rather than values, so blanks are counted too.

func NewPivot

func NewPivot(src *Sheet, r Rect) Pivot

NewPivot starts a pivot over r on src with nothing chosen yet and both grand totals on, as Sheets' new pivot tables.

type PivotFilter

type PivotFilter struct {
	Col      int
	Criteria Criteria
}

PivotFilter leaves out the source rows whose value in Col doesn't meet Criteria, as a filter's column does.

type PivotGroup

type PivotGroup struct {
	Col  int  // column on the source sheet
	Desc bool // Z to A, or largest first
	// SortBy orders the groups by their label (0) or by the grand total
	// of Values[SortBy-1].
	SortBy int
}

PivotGroup is a column of the source whose distinct values become rows or columns of the pivot.

type PivotInfo

type PivotInfo struct {
	Records  int // source rows summarized
	Groups   int // groups of the row fields
	Cells    int // cells of the results
	Failed   bool
	Duration time.Duration
}

PivotInfo describes one pivot recomputation, for telemetry. It holds counts only, never contents.

type PivotValue

type PivotValue struct {
	Col       int
	Summarize Summarize
	ShowAs    ShowAs
	Name      string // the header; "" for Sheets' "SUM of Sales"
}

PivotValue is a column of the source summarized per group.

type RecalcInfo

type RecalcInfo struct {
	Full      bool // every formula, as after loading
	Evaluated int  // cells marked dirty and recomputed
	Cells     int  // cells stored on every sheet, including formatting-only ones
	Volatile  int  // volatile formulas on every sheet, recomputed every time
	Circular  bool
	// Duration includes the pivot tables the recalculation refreshed,
	// and the recalculation of what reads their results.
	Duration time.Duration
}

RecalcInfo describes one recalculation, for telemetry. It holds counts only, never contents.

type Rect

type Rect = formula.Rect

Rect is an inclusive rectangular range of cells.

func NewRect

func NewRect(a, b Addr) Rect

NewRect returns the normalized rectangle spanning a and b.

func ParseRange

func ParseRange(s string) (Rect, bool)

ParseRange parses "A1", "A1:B3" or 1-2-3 style "A1..B3".

type RemoteAnswer

type RemoteAnswer = functions.RemoteAnswer

The questions and answers are the function library's (functions/remote.go); the engine's API names them too.

type RemoteCall

type RemoteCall = functions.RemoteCall

The questions and answers are the function library's (functions/remote.go); the engine's API names them too.

type RemoteSource

type RemoteSource = functions.RemoteSource

The questions and answers are the function library's (functions/remote.go); the engine's API names them too.

type Sheet

type Sheet struct {
	// contains filtered or unexported fields
}

Sheet is a sparse worksheet, one of a Workbook's sheets.

func New

func New() *Sheet

New returns an empty worksheet, the only sheet of a new workbook.

func Read

func Read(r io.Reader) (*Sheet, error)

Read loads a file written by Write, of this or an earlier version, and returns the sheet that was shown when it was saved.

func ReadTraced

func ReadTraced(r io.Reader, trace any) (*Sheet, error)

ReadTraced is Read giving the workbook trace (see SetTrace) before it recalculates, so that recalculation nests in the caller's span.

func (*Sheet) AddChart

func (s *Sheet) AddChart(c Chart) int

AddChart adds a chart on top of the others and returns its index.

func (*Sheet) Addrs

func (s *Sheet) Addrs() []Addr

Addrs returns every non-blank cell in row-major order.

func (*Sheet) AdjustDecimals

func (s *Sheet) AdjustDecimals(r Rect, delta int)

AdjustDecimals shows delta more (or fewer) decimal places in every non-blank number cell of r, starting from what each cell shows now.

func (*Sheet) Batch

func (s *Sheet) Batch(c Change, fn func() error) error

Batch runs fn as a single undo step: everything it changes is undone together, and formulas are recalculated once at the end. Batches nest; inner ones join the outermost.

func (*Sheet) Book

func (s *Sheet) Book() *Workbook

Book returns the workbook the sheet belongs to.

func (*Sheet) CanRedo

func (s *Sheet) CanRedo() bool

func (*Sheet) CanUndo

func (s *Sheet) CanUndo() bool

func (*Sheet) Cell

func (s *Sheet) Cell(a Addr) *Cell

Cell returns the cell at a, or nil if it has neither contents nor formatting. Use Blank to test for contents.

func (*Sheet) CellFormat

func (s *Sheet) CellFormat(a Addr) Format

CellFormat returns the number format the cell at a has, its own or its row's or column's, without the one a formula infers.

func (*Sheet) CellStyle

func (s *Sheet) CellStyle(a Addr) Style

CellStyle returns the text style the cell at a shows: its own, or its row's or column's.

func (*Sheet) ChartData

func (s *Sheet) ChartData(c Chart) ChartData

ChartData reads a chart's cells. Series names and labels are the cells' text as displayed.

func (*Sheet) Charts

func (s *Sheet) Charts() []Chart

Charts returns the sheet's charts, bottom first.

func (*Sheet) ClearFormatting

func (s *Sheet) ClearFormatting(r Rect)

ClearFormatting resets the format and style of every cell in r, as Sheets' Format > Clear formatting.

func (*Sheet) ClearHistory

func (s *Sheet) ClearHistory()

func (*Sheet) ColFormats

func (s *Sheet) ColFormats() map[int]Format

ColFormats and RowFormats return the columns and rows that have a format or style of their own, by index.

func (*Sheet) ColStyles

func (s *Sheet) ColStyles() map[int]Style

ColStyles and RowStyles are the same for text styles.

func (*Sheet) ColWidth

func (s *Sheet) ColWidth(c int) int

ColWidth returns the display width of column c.

func (*Sheet) ColumnFiltered

func (s *Sheet) ColumnFiltered(col int) bool

ColumnFiltered reports whether the filter has criteria for column col.

func (*Sheet) Copy

func (s *Sheet) Copy(r Rect) *Clip

Copy snapshots the cells in r, and what formatting they show, for pasting. Whole columns or rows are trimmed to the cells they hold, keeping their line formats.

func (*Sheet) CreateFilter

func (s *Sheet) CreateFilter(r Rect)

CreateFilter puts a filter on r, whose first row is the header row.

func (*Sheet) Decimal

func (s *Sheet) Decimal() bool

Decimal and SetDecimal on a sheet are its workbook's.

func (*Sheet) DefineName

func (s *Sheet) DefineName(name string, r Rect) error

func (*Sheet) DeleteChart

func (s *Sheet) DeleteChart(i int)

DeleteChart removes chart i.

func (*Sheet) DeleteCols

func (s *Sheet) DeleteCols(at, n int)

DeleteCols deletes n columns starting at column at.

func (*Sheet) DeleteName

func (s *Sheet) DeleteName(name string) error

func (*Sheet) DeleteRows

func (s *Sheet) DeleteRows(at, n int)

DeleteRows deletes n rows starting at row at. References to deleted cells become #REF!; ranges that lose some of their rows shrink.

func (*Sheet) Dependents

func (s *Sheet) Dependents(a Addr) []Target

Dependents returns the formula cells that read a directly, through a reference, a range or a named range: those on this sheet first in row-major order, then those on other sheets in tab order.

func (*Sheet) DisplayFormat

func (s *Sheet) DisplayFormat(a Addr) Format

DisplayFormat returns the format the cell at a is shown with: its own, its row's or column's, or for Automatic, the one inferred from its formula (=DATE() shows a date, =SUM(B2:B4) of currency shows currency).

func (*Sheet) Edge

func (s *Sheet) Edge(a Addr, dc, dr int) Addr

Edge returns where a data-edge jump (Ctrl+arrow in Excel, End+arrow in 1-2-3) from a in direction (dc, dr) lands. Inside a block of filled cells it stops at the block's last cell; from a blank cell, or at the end of a block, it goes to the next filled cell. With nothing filled ahead it stops at the edge of the worksheet. Rows the filter hides are skipped. Blank stretches are jumped over through the index of filled cells, so a jump costs what the block it walks holds, not the empty rows past it.

func (*Sheet) EditName

func (s *Sheet) EditName(old, name string, r Rect) error

func (*Sheet) EraseRange

func (s *Sheet) EraseRange(r Rect)

EraseRange clears the contents of every cell in r, keeping their formatting as Sheets' Delete does.

func (*Sheet) ExplainError

func (s *Sheet) ExplainError(a Addr) string

ExplainError says why the cell at a shows an error, for the context line: where the error starts and what went wrong, e.g. "Division by zero in B3/0", or "From B5: division by zero in B3/0" when it comes from another cell. It is empty for cells without errors.

func (*Sheet) FillDown

func (s *Sheet) FillDown(r Rect) (Rect, error)

FillDown copies the top row of r into the rest of it, adjusting references (Ctrl+D). A single-row range fills from the row above. When the top rows of r start a series and the rest is blank (1, 2 and then empty cells), it continues the series instead, as dragging the fill handle would.

func (*Sheet) FillEntry

func (s *Sheet) FillEntry(r Rect, origin Addr, input string) error

FillEntry stores input in every cell of r as if it had been typed at origin and copied to each cell, adjusting references (Ctrl+Enter).

func (*Sheet) FillRight

func (s *Sheet) FillRight(r Rect) (Rect, error)

FillRight copies the left column of r into the rest of it (Ctrl+R). A single-column range fills from the column to the left. Like FillDown, it continues a series started in the leftmost columns.

func (*Sheet) FillSeries

func (s *Sheet) FillSeries(src, dst Rect) (Rect, error)

FillSeries extends src over dst, which contains it and reaches past it along one axis: down or up, right or left. Each column (or row) of src is continued on its own. It returns the range filled, as one undo step.

func (*Sheet) FilledBounds

func (s *Sheet) FilledBounds(r Rect) (Rect, bool)

FilledBounds returns the smallest range holding every non-blank cell of r, and false if there is none.

func (*Sheet) Filter

func (s *Sheet) Filter() *Filter

Filter returns a copy of the sheet's filter, or nil if it has none.

func (*Sheet) FilterColumn

func (s *Sheet) FilterColumn(col int, cr Criteria)

FilterColumn sets the criteria for column col of the filter.

func (*Sheet) FilterRange

func (s *Sheet) FilterRange() (Rect, bool)

FilterRange returns the filter's range, and false if there is no filter.

func (*Sheet) FilterValues

func (s *Sheet) FilterValues(col int) []FilterValue

FilterValues lists the distinct values in column col of the filter's data rows, among the rows the other columns' criteria let through, as Sheets' "Filter by values" does. Numbers come first in numeric order, then text alphabetically, then blanks.

func (*Sheet) Find

func (s *Sheet) Find(query string, o FindOptions) ([]Addr, error)

Find returns the cells matching query in reading order: row by row, left to right.

func (*Sheet) Frozen

func (s *Sheet) Frozen() (rows, cols int)

Frozen returns how many rows and columns are frozen at the top and left.

func (*Sheet) GuessChart

func (s *Sheet) GuessChart(r Rect) Chart

GuessChart sets up a chart over r the way Sheets does: series down columns, a header row when the first row is text over numbers, and category labels when the first column is text.

func (*Sheet) Hidden

func (s *Sheet) Hidden() bool

Hidden reports whether the sheet is hidden.

func (*Sheet) HiddenRows

func (s *Sheet) HiddenRows() int

HiddenRows returns how many rows the filter hides.

func (*Sheet) InPivot

func (s *Sheet) InPivot(r Rect) bool

InPivot reports whether r overlaps the pivot table's results, which can't be edited.

func (*Sheet) InsertCols

func (s *Sheet) InsertCols(at, n int) error

InsertCols inserts n blank columns before column at.

func (*Sheet) InsertRows

func (s *Sheet) InsertRows(at, n int) error

InsertRows inserts n blank rows before row at, shifting the rows below down and adjusting every reference to them.

func (*Sheet) Len

func (s *Sheet) Len() int

Len returns the number of non-blank cells.

func (s *Sheet) Link(a Addr) string

Link returns the address a cell links to: its text when that is a URL (http, https or mailto), or the target of a HYPERLINK formula. It is empty for other cells.

func (*Sheet) Live

func (s *Sheet) Live() bool

Live reports whether the sheet is in its workbook, i.e. not deleted.

func (*Sheet) Load

func (s *Sheet) Load(a Addr, input string, f Format, st Style) error

Load stores an entry at a with its number format and style, without recalculating or recording undo. With an Automatic format the entry implies one as if typed ("$5" is currency, "9/26/2026" a date). A formula that fails to parse is rejected with a *ParseError and nothing is stored. Call RecalcAll when every cell is in.

func (*Sheet) LoadColWidth

func (s *Sheet) LoadColWidth(c, w int)

LoadColWidth sets column c's width, as a loader does: without recording undo or recalculating.

func (*Sheet) LoadFilter

func (s *Sheet) LoadFilter(f *Filter)

LoadFilter puts filter f on the sheet (nil removes it), as a loader does: without recording undo. Its criteria apply once values are computed, as they do whenever values change.

func (*Sheet) LoadFrozen

func (s *Sheet) LoadFrozen(rows, cols int)

LoadFrozen freezes the first rows rows and cols columns, as a loader does: without recording undo. SetFrozen is the undoable way.

func (*Sheet) LoadLineFormat

func (s *Sheet) LoadLineFormat(row bool, n int, f Format, st Style)

LoadLineFormat gives a whole column (row false) or row a format and style, as an importer does, without recording undo or touching its cells; column -1 is the whole sheet.

func (*Sheet) LookupName

func (s *Sheet) LookupName(name string) (Name, bool)

func (*Sheet) Move

func (s *Sheet) Move(src Rect, to Addr) (Rect, error)

Move moves the cells in src so its top-left corner lands on to, as cut and paste does in Sheets, with the formatting they show; whole columns or rows take their line formats along. Formulas anywhere that referred to the moved cells follow them; references to cells the move overwrote become #REF!. It returns the destination range.

func (*Sheet) MoveTo

func (s *Sheet) MoveTo(dst *Sheet, src Rect, to Addr) (Rect, error)

MoveTo moves the cells in src to sheet dst, src's top-left corner landing on to, as cutting on one sheet and pasting on another does in Sheets. Formulas anywhere that read the moved cells follow them to dst, naming its sheet where they need to; the moved formulas keep reading what they read, naming this sheet for cells that stayed behind. References to cells the move overwrote become #REF!.

func (*Sheet) Name

func (s *Sheet) Name() string

Name returns the sheet's name.

func (*Sheet) NameUsers

func (s *Sheet) NameUsers(name string) int

func (*Sheet) NamedSheets

func (s *Sheet) NamedSheets(a Addr) []string

NamedSheets returns the sheet names the formula at a names, as written and without repeats (in any case), or nil for anything else. Names of sheets that don't exist are included: exporters check them.

func (*Sheet) Names

func (s *Sheet) Names() []Name

func (*Sheet) NextFilledCol

func (s *Sheet) NextFilledCol(row, col, dir, limit int) (int, bool)

NextFilledCol returns the nearest column of row, from col on in direction dir (1 or -1) and no further than limit, whose cell has contents, looking only at the columns that hold any.

func (*Sheet) NextShownRow

func (s *Sheet) NextShownRow(r, d int) (int, bool)

NextShownRow returns the first row from r+d on (d is 1 or -1) that the filter doesn't hide, jumping over the hidden blank rows at the end of its range at once, and false past the edge of the sheet.

func (*Sheet) Paste

func (s *Sheet) Paste(c *Clip, dst Rect, values bool) (Rect, error)

Paste writes the clip into dst and returns the range written. Formulas shift their relative references by the distance pasted, as in Sheets; with values set, only the computed values are pasted, keeping the destination's formatting. Otherwise each cell shows the formatting its source showed (see clipfmt.go). Like Sheets, a destination that is an exact multiple of the clip's size is tiled; otherwise the clip is pasted once at dst's top-left corner.

func (*Sheet) Pivot

func (s *Sheet) Pivot() (Pivot, bool)

Pivot returns a copy of the sheet's pivot table, and false if it has none.

func (*Sheet) PivotError

func (s *Sheet) PivotError() string

PivotError says why the pivot shows #REF!, or "" when it doesn't.

func (*Sheet) PivotRange

func (s *Sheet) PivotRange() (Rect, bool)

PivotRange returns the cells the pivot's results cover, from A1 (at least A1, even while it shows nothing), and false without a pivot.

func (*Sheet) PivotSource

func (s *Sheet) PivotSource() *Sheet

PivotSource returns the sheet the pivot reads, or nil when no sheet has its name.

func (*Sheet) Precedents

func (s *Sheet) Precedents(a Addr) []Target

Precedents returns the cells and ranges the formula at a reads, in the order the formula mentions them, with named ranges resolved and repeats dropped. References to sheets that don't exist are left out. It is empty for anything but a formula.

func (*Sheet) RangeStats

func (s *Sheet) RangeStats(r Rect) Stats

RangeStats computes Stats over r. The result is kept until a cell or value changes. A selection over a large, well-filled sheet is summed from the cells' statistics index (see rangeStats), so changing it costs a block per column plus the rows at its ends, not a read of every cell.

func (*Sheet) RecalcAll

func (s *Sheet) RecalcAll()

RecalcAll recomputes every formula in the workbook. Loaders call it once the sheets are built, so it also starts a fresh undo history: loading isn't undoable.

func (*Sheet) RecalcVolatile

func (s *Sheet) RecalcVolatile()

RecalcVolatile recomputes volatile formulas and their dependents on every sheet, e.g. after remote answers arrive. It doesn't touch the undo history.

func (*Sheet) Redo

func (s *Sheet) Redo() (Change, bool)

func (*Sheet) Region

func (s *Sheet) Region(a Addr) Rect

Region returns the block of data around a, as Sheets picks the range to sort or filter when a single cell is selected: filled cells connected to a (diagonals count), and anything touching their bounding box, until nothing more touches it. A blank cell with no filled neighbors is a region of its own.

func (*Sheet) RemoteCalls

func (s *Sheet) RemoteCalls(a Addr) []RemoteCall

RemoteCalls returns the questions the formula at a asks, with their current inputs, so the UI can show details or re-ask them.

func (*Sheet) RemoveFilter

func (s *Sheet) RemoveFilter()

RemoveFilter removes the filter, showing every row again.

func (*Sheet) Replace

func (s *Sheet) Replace(a Addr, query, repl string, o FindOptions) (bool, error)

Replace replaces matches of query in the cell at a and reports whether the cell changed. Formula cells are only changed when searching within formulas, as in Sheets. A replacement that turns a formula invalid is returned as an error and leaves the cell unchanged.

func (*Sheet) ReplaceAll

func (s *Sheet) ReplaceAll(query, repl string, o FindOptions) (int, error)

ReplaceAll replaces every match and returns how many cells changed. It stops at the first cell whose replacement is an invalid formula.

func (*Sheet) RowFormats

func (s *Sheet) RowFormats() map[int]Format

func (*Sheet) RowHidden

func (s *Sheet) RowHidden(r int) bool

RowHidden reports whether the filter hides row r.

func (*Sheet) RowStyles

func (s *Sheet) RowStyles() map[int]Style

func (*Sheet) Seal

func (s *Sheet) Seal()

func (*Sheet) Set

func (s *Sheet) Set(a Addr, input string) error

Set stores an entry at a and recalculates affected cells. An empty input erases the contents but keeps the cell's formatting. A formula that fails to parse is rejected with a *ParseError and the sheet is left unchanged. A pivot table's results can't be set: that's ErrPivotEdit.

func (*Sheet) SetChart

func (s *Sheet) SetChart(i int, c Chart, label string)

SetChart replaces chart i, as one undo step described by label, e.g. "move chart".

func (*Sheet) SetColWidth

func (s *Sheet) SetColWidth(c, w int)

SetColWidth sets column c's width; w <= 0 resets it to the default.

func (*Sheet) SetDecimal

func (s *Sheet) SetDecimal(on bool)

func (*Sheet) SetFormat

func (s *Sheet) SetFormat(r Rect, f Format)

SetFormat gives every cell in r the number format f, including blank cells, which keep it for when something is typed. Whole columns and rows keep it as their line's format rather than on each cell.

func (*Sheet) SetFrozen

func (s *Sheet) SetFrozen(rows, cols int)

SetFrozen freezes the first rows rows and cols columns (0 unfreezes).

func (*Sheet) SetPivot

func (s *Sheet) SetPivot(p Pivot, label string) error

SetPivot replaces the sheet's pivot definition as one undo step, labelled label ("edit pivot table" when empty).

func (*Sheet) SetRemote

func (s *Sheet) SetRemote(r RemoteSource)

SetRemote on a sheet is its workbook's.

func (*Sheet) SetStyle

func (s *Sheet) SetStyle(r Rect, fn func(*Style))

SetStyle changes the text style of every cell in r with fn, e.g. to turn on bold while keeping italics. Callers wanting a specific undo label ("bold B2:B5") wrap it in Batch.

func (*Sheet) SheetFormat

func (s *Sheet) SheetFormat() (Format, Style)

SheetFormat returns the format and style of the whole sheet, which every cell without its own, its row's or its column's shows.

func (*Sheet) ShownText

func (s *Sheet) ShownText(a Addr) string

ShownText is the cell's value as its format displays it, with no width limit: what filters and the values list compare.

func (*Sheet) SortRange

func (s *Sheet) SortRange(r Rect, keys []SortKey)

SortRange sorts the rows of r by keys, first key first, as Sheets' Data > Sort range does (r excludes any header row). The sort is stable, so rows that tie keep their order. Only the cells inside r move. Formulas move with their rows and their relative references shift by the distance moved, as if copied there; references to the sorted cells from elsewhere are left alone. The whole sort is one undo step.

Only rows holding cells are sorted: rows whose keys are all blank go last in their order, as blank rows do, so the cost is the rows with data, however tall r is.

func (*Sheet) StateID

func (s *Sheet) StateID() int

func (*Sheet) Undo

func (s *Sheet) Undo() (Change, bool)

func (*Sheet) Unload

func (s *Sheet) Unload(a Addr)

Unload removes a cell a loader stored, as an importer does with a row that doesn't fit whole.

func (*Sheet) UsedRange

func (s *Sheet) UsedRange() (Rect, bool)

UsedRange returns the smallest range from A1 covering every non-blank cell, and false if the sheet is empty.

func (*Sheet) Value

func (s *Sheet) Value(a Addr) Value

Value returns the computed value at a.

func (*Sheet) Widths

func (s *Sheet) Widths() map[int]int

Widths returns the columns that have a non-default width.

func (*Sheet) Write

func (s *Sheet) Write(w io.Writer) error

Write saves the workbook the sheet belongs to; see Workbook.Write.

type ShowAs

type ShowAs uint8

ShowAs is how a summarized value shows: as itself, or as a share of a total, as Sheets' "Show as".

const (
	ShowValue ShowAs = iota
	ShowPctRow
	ShowPctColumn
	ShowPctTotal
)

func ParseShowAs

func ParseShowAs(name string) (ShowAs, bool)

ParseShowAs is the inverse of ShowAs.String.

func ShowAsList

func ShowAsList() []ShowAs

ShowAsList lists the choices in Sheets' order.

func (ShowAs) String

func (s ShowAs) String() string

func (ShowAs) Title

func (s ShowAs) Title() string

type SortKey

type SortKey struct {
	Col  int
	Desc bool // Z to A
}

SortKey is one column to sort by.

type Stats

type Stats struct {
	Sum         float64
	Count, Nums int
}

Stats summarizes the values in r, as shown in the status line for a selection. Count is non-blank cells, Nums is numeric cells.

type Style

type Style struct {
	Bold, Italic, Underline, Strikethrough bool
	Align                                  Align
	// contains filtered or unexported fields
}

Style is a cell's text style. It is a plain value so cells can be copied freely.

func (Style) IsZero

func (s Style) IsZero() bool

IsZero reports whether s is the default style.

type Summarize

type Summarize uint8

Summarize is how a pivot value summarizes a group's cells, as Sheets' "Summarize by". Each is one entry of summaries.

const (
	SumBy Summarize = iota
	CountABy
	CountBy
	CountUniqueBy
	AverageBy
	MaxBy
	MinBy
	// CountRowsBy counts rows, blank or not. Sheets has no such choice;
	// frequency tables use it so blank values are counted.
	CountRowsBy
)

func ParseSummarize

func ParseSummarize(name string) (Summarize, bool)

ParseSummarize is the inverse of Summarize.String.

func Summaries

func Summaries() []Summarize

Summaries lists the choices of "Summarize by", in Sheets' order.

func (Summarize) Desc

func (f Summarize) Desc() string

func (Summarize) String

func (f Summarize) String() string

func (Summarize) Title

func (f Summarize) Title() string

type Target

type Target struct {
	Sheet *Sheet
	Range Rect
}

Target is a traced cell or range and the sheet it is on.

type Value

type Value = value.Value

Value is the computed contents of a cell.

type Workbook

type Workbook struct {

	// Circular is set when the last recalculation found a cycle.
	Circular bool
	// contains filtered or unexported fields
}

A Workbook is an ordered list of sheets, as a Google Sheets spreadsheet: each sheet has its own cells, column widths, frozen panes, filter and charts, while named ranges, the undo history and recalculation are shared, so a formula on one sheet can read another (=Sheet2!A1, ='Q3 plan'!B2:C9) and one undo step can span sheets.

Formulas refer to other sheets by name. Renaming a sheet rewrites the formulas that name it; deleting one leaves them as written, showing #REF! ("Unresolved sheet name"), until a sheet of that name exists again, as in Sheets.

func NewBook

func NewBook() *Workbook

NewBook returns a workbook with one empty sheet, Sheet1.

func ReadBook

func ReadBook(r io.Reader) (*Workbook, error)

ReadBook loads a workbook written by Write, of this or an earlier version.

func (*Workbook) Active

func (w *Workbook) Active() int

Active returns the index of the sheet last shown, as saved in the file.

func (*Workbook) AddSheet

func (w *Workbook) AddSheet(name string, at int) (*Sheet, error)

AddSheet inserts a new, empty sheet at index at (clamped to the ends), as one undo step. An empty name picks the next SheetN.

func (*Workbook) Batch

func (w *Workbook) Batch(c Change, fn func() error) error

Batch runs fn as a single undo step across sheets, as Sheet.Batch; the step is shown on c.Sheet when undone.

func (*Workbook) Begin

func (w *Workbook) Begin(c Change) (end func())

Begin opens an undo step that stays open until the returned function is called, for changes made over several calls that undo together, such as a macro run. Changes in between join it as in a Batch, and Undo and Redo do nothing while it is open. Call Settle to see the values of formulas changed so far.

func (*Workbook) CanRedo

func (w *Workbook) CanRedo() bool

func (*Workbook) CanUndo

func (w *Workbook) CanUndo() bool

CanUndo and CanRedo report whether there is a step to undo or redo.

func (*Workbook) ClearHistory

func (w *Workbook) ClearHistory()

ClearHistory forgets all undo and redo steps.

func (*Workbook) CreatePivot

func (w *Workbook) CreatePivot(src *Sheet, r Rect, name string, p Pivot) (*Sheet, error)

CreatePivot adds a sheet named name ("" for the next Pivot Table N) right after src, holding p over r on src, as one undo step.

func (*Workbook) Decimal

func (w *Workbook) Decimal() bool

Decimal reports whether the workbook computes in decimal.

func (*Workbook) DefaultSummarize

func (w *Workbook) DefaultSummarize(p Pivot, col int) Summarize

DefaultSummarize is how a new value summarizes column col, as in Sheets: SUM when the column holds a number, COUNTA otherwise.

func (*Workbook) DefineName

func (w *Workbook) DefineName(name string, s *Sheet, r Rect) error

DefineName names the range r on sheet s, as one undo step.

func (*Workbook) DeleteMacro

func (w *Workbook) DeleteMacro(name string) bool

DeleteMacro removes the named macro as an undo step, reporting whether there was one.

func (*Workbook) DeleteName

func (w *Workbook) DeleteName(name string) error

DeleteName removes a named range, as one undo step. Formulas that use it show #NAME? until it is defined again.

func (*Workbook) DeleteSheet

func (w *Workbook) DeleteSheet(s *Sheet) error

DeleteSheet removes s, as one undo step. Formulas on other sheets that refer to it show #REF! until it's restored or another sheet takes its name. The last sheet can't be deleted.

func (*Workbook) DuplicateSheet

func (w *Workbook) DuplicateSheet(s *Sheet) (*Sheet, error)

DuplicateSheet copies s, cells, widths, frozen panes, filter and charts, to a new sheet right after it named "Copy of ...", as Sheets' Duplicate. Formulas are copied as written, so references without a sheet name read the copy's own cells.

func (*Workbook) EditName

func (w *Workbook) EditName(old, name string, s *Sheet, r Rect) error

EditName renames the named range old and points it at r on sheet s, as one undo step. Formulas that use it are rewritten to the new name, as in Sheets.

func (*Workbook) FieldName

func (w *Workbook) FieldName(p Pivot, col int) string

FieldName is the header of column col in the pivot's source, or "Column B" when the header is blank.

func (*Workbook) HiddenSheets

func (w *Workbook) HiddenSheets() []*Sheet

HiddenSheets returns the hidden sheets, in tab order.

func (*Workbook) HideSheet

func (w *Workbook) HideSheet(s *Sheet) error

HideSheet hides s, as one undo step. The last visible sheet can't be hidden.

func (*Workbook) HistoryBytes

func (w *Workbook) HistoryBytes() int64

HistoryBytes estimates the memory the undo steps hold.

func (*Workbook) Index

func (w *Workbook) Index(s *Sheet) int

Index returns s's position in tab order, or -1 if it was deleted.

func (*Workbook) InsertBook

func (w *Workbook) InsertBook(src *Workbook, at int, label string) (ImportResult, error)

InsertBook moves the sheets of src, an imported workbook, into w at index at (clamped to the ends; the UI puts them after the sheet shown), with src's named ranges, as one undo step labelled label. A sheet whose name w already has gets a number ("Sales 2"), and src's formulas follow the new name; a named range whose name w already has is left out. src is used up.

func (*Workbook) Len

func (w *Workbook) Len() int

Len returns the number of sheets.

func (*Workbook) Lookup

func (w *Workbook) Lookup(name string) *Sheet

Lookup finds a sheet by name, ignoring case.

func (*Workbook) LookupName

func (w *Workbook) LookupName(name string) (Name, bool)

LookupName finds a named range, ignoring case.

func (*Workbook) Macro

func (w *Workbook) Macro(name string) (Macro, bool)

Macro finds a macro by name, ignoring case.

func (*Workbook) MacroForKey

func (w *Workbook) MacroForKey(key string) (Macro, bool)

MacroForKey finds the macro a shortcut digit runs.

func (*Workbook) MacroOrigin

func (w *Workbook) MacroOrigin() string

MacroOrigin identifies the computer the workbook's macros were made or trusted on, as saved in the file; "" when unknown. The UI compares it with its own to decide whether to ask before running a macro from a file made elsewhere.

func (*Workbook) Macros

func (w *Workbook) Macros() []Macro

Macros returns the saved macros in the order they were added.

func (*Workbook) MoveSheet

func (w *Workbook) MoveSheet(s *Sheet, to int)

MoveSheet moves s to index to in tab order, as one undo step.

func (*Workbook) NameUsers

func (w *Workbook) NameUsers(name string) int

NameUsers returns how many formulas mention the name.

func (*Workbook) Names

func (w *Workbook) Names() []Name

Names returns the named ranges, sorted by name.

func (*Workbook) NextPivotName

func (w *Workbook) NextPivotName() string

NextPivotName is the name Sheets gives a new pivot sheet: Pivot Table 1, then 2 and so on.

func (*Workbook) PivotFilterValues

func (w *Workbook) PivotFilterValues(p Pivot, col int) []FilterValue

PivotFilterValues lists the distinct values of column col of the pivot's source, among the rows its other filters let through, as a filter's values list does.

func (*Workbook) RecalcAll

func (w *Workbook) RecalcAll()

RecalcAll recomputes every formula and clears the undo history.

func (*Workbook) RecalcAnswered

func (w *Workbook) RecalcAnswered(calls []RemoteCall)

RecalcAnswered recomputes the formulas that were waiting for the answers to calls, and what depends on them, on every sheet: with thousands of JEV cells, an answer costs the cells that asked it, not all of them. It doesn't touch the undo history.

func (*Workbook) Redo

func (w *Workbook) Redo() (Change, bool)

Redo reapplies the last undone step and describes it.

func (*Workbook) RenameSheet

func (w *Workbook) RenameSheet(s *Sheet, name string) error

RenameSheet renames s, as one undo step, rewriting every formula that refers to it by its old name.

func (*Workbook) ReplaceSheet

func (w *Workbook) ReplaceSheet(dst, s *Sheet, label string) ([]ChartFate, error)

ReplaceSheet puts s, the sheet of an imported workbook, in the place of dst, as one undo step labelled label: it takes dst's name and position, so formulas reading dst read it, and named ranges on dst move to it. dst's charts stay, drawing s's data (see keepCharts), and it returns what became of each. dst's cells and the rest go; undo brings them back.

func (*Workbook) SaveMacro

func (w *Workbook) SaveMacro(old string, mc Macro, label string) error

SaveMacro stores mc in place of the macro named old, or adds it when old is "", as one undo step labelled label. Names are unique ignoring case, and so are shortcuts.

func (*Workbook) Seal

func (w *Workbook) Seal()

Seal ends a run of column width changes, so the next one starts a new undo step. The UI calls it between user actions.

func (*Workbook) SetActive

func (w *Workbook) SetActive(s *Sheet)

SetActive records which sheet is shown, for the file. It isn't an edit.

func (*Workbook) SetDecimal

func (w *Workbook) SetDecimal(on bool)

SetDecimal turns decimal arithmetic on or off for every sheet, as one undo step, and recalculates every formula.

func (*Workbook) SetMacroOrigin

func (w *Workbook) SetMacroOrigin(origin string)

SetMacroOrigin records where the macros were made or trusted. It isn't an edit: it changes nothing a user sees, and is saved with the next save.

func (*Workbook) SetRemote

func (w *Workbook) SetRemote(r RemoteSource)

SetRemote sets what answers the workbook's JEV functions: nil when no API key is configured, and the functions then evaluate to ErrNoRemote. It recomputes them, so a loaded file's questions are asked.

func (*Workbook) SetTrace

func (w *Workbook) SetTrace(trace any)

SetTrace gives the workbook its owner's trace, opaque to the engine: a *telemetry.Trace from the program or import that holds the workbook, which only its goroutine uses, as with the workbook itself.

func (*Workbook) Settle

func (w *Workbook) Settle()

Settle recalculates what the open step has changed so far, so formulas read inside it (by a macro, or a command it runs) see current values. Outside a step there is nothing pending.

func (*Workbook) Sheet

func (w *Workbook) Sheet(i int) *Sheet

Sheet returns the sheet at index i in tab order.

func (*Workbook) Sheets

func (w *Workbook) Sheets() []*Sheet

Sheets returns the sheets in tab order.

func (*Workbook) StateID

func (w *Workbook) StateID() int

StateID identifies the workbook's contents in its undo history: undoing back to a saved state returns the ID it had when saved, so the UI can tell whether there are unsaved changes.

func (*Workbook) Undo

func (w *Workbook) Undo() (Change, bool)

Undo reverts the last step and describes it.

func (*Workbook) UndoLabel

func (w *Workbook) UndoLabel() string

UndoLabel describes the step Undo would revert, e.g. "clear B3:B5", or "" when there is none.

func (*Workbook) UnhideSheet

func (w *Workbook) UnhideSheet(s *Sheet) error

UnhideSheet shows s again, as one undo step.

func (*Workbook) ValueTitle

func (w *Workbook) ValueTitle(p Pivot, v PivotValue) string

ValueTitle is the header of a value: its name, or Sheets' "SUM of Sales".

func (*Workbook) Visible

func (w *Workbook) Visible() []*Sheet

Visible returns the sheets that aren't hidden, in tab order.

func (*Workbook) Write

func (w *Workbook) Write(out io.Writer) error

Write saves the workbook as JSON, storing each cell's input as typed and its formatting. Cells go one per line in row-major order so diffs read naturally.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL