excel

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Rendered for windows/amd64

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddOption added in v0.7.0

type AddOption func(*addOptions)

AddOption configures Worksheets.Add. Build with AddBefore/AddAfter/AddName.

func AddAfter added in v0.7.0

func AddAfter(anchor Worksheet) AddOption

AddAfter inserts the new sheet after the given anchor sheet.

func AddBefore added in v0.7.0

func AddBefore(anchor Worksheet) AddOption

AddBefore inserts the new sheet before the given anchor sheet.

func AddName added in v0.7.0

func AddName(name string) AddOption

AddName names the new sheet after creation. Excel's `Worksheets.Add` does not accept a name argument, so we set `Name` on the result.

type Application added in v0.4.0

type Application interface {
	sugar.Chain
	// Workbooks returns the collection of all open workbooks.
	Workbooks() Workbooks
	// Books is the xlwings-style alias for Workbooks.
	Books() Workbooks
	// ActiveWorkbook returns the workbook that is currently active.
	ActiveWorkbook() Workbook
	// Quit quits the Excel application. The instance still exists in memory
	// until released; use Kill if Quit hangs.
	Quit() error
	// Kill terminates the underlying Excel process via `taskkill /PID`.
	// Equivalent to xlwings' `app.kill()`. Use only as a last resort —
	// pending writes are lost.
	Kill() error

	// Version returns the Excel application version string (e.g. "16.0").
	Version() (string, error)
	// PID returns the underlying Excel process ID.
	PID() (int32, error)
	// Hwnd returns the top-level window handle of the Excel instance.
	Hwnd() (int32, error)

	// Visible is the Go equivalent of xlwings' `App.visible` property getter.
	// It returns a sugar.Chain representing the COM `Visible` property value;
	// call .Value() to materialize as a bool.
	Visible() sugar.Chain
	// SetVisible is the Go equivalent of xlwings' `App.visible` property setter.
	// It sets Excel's visibility and returns the Application for fluent chaining.
	SetVisible(v bool) Application

	// DisplayAlerts is the Go equivalent of xlwings' `App.display_alerts`
	// property getter. It returns a sugar.Chain representing the COM
	// `DisplayAlerts` property value; call .Value() to materialize as a bool.
	DisplayAlerts() sugar.Chain
	// SetDisplayAlerts is the Go equivalent of xlwings' `App.display_alerts`
	// property setter. Set to false to suppress prompts and alert messages;
	// Excel will choose the default response. Returns the Application for
	// fluent chaining.
	SetDisplayAlerts(v bool) Application

	// ScreenUpdating is the Go equivalent of xlwings' `App.screen_updating`
	// property getter. It returns a sugar.Chain representing the COM
	// `ScreenUpdating` property value; call .Value() to materialize as a bool.
	ScreenUpdating() sugar.Chain
	// SetScreenUpdating is the Go equivalent of xlwings' `App.screen_updating`
	// property setter. Turn off to speed up scripts; remember to turn back on
	// when the script ends. Returns the Application for fluent chaining.
	SetScreenUpdating(v bool) Application

	// Calculation returns the current calculation mode.
	Calculation() (Calculation, error)
	// SetCalculation sets the calculation mode. Set to CalculationManual to
	// stop Excel from recalculating during bulk writes.
	SetCalculation(c Calculation) Application
}

Application is the Go equivalent of xlwings' `App` object. It wraps the `Excel.Application` COM object and is the root of the Excel object model.

xlwings reference: https://docs.xlwings.org/en/stable/api/app.html

func GetApplication added in v0.4.0

func GetApplication(ctx sugar.Context) Application

GetApplication attaches to a running Excel instance and tracks it on the given context's arena.

func NewApplication added in v0.4.0

func NewApplication(ctx sugar.Context) Application

NewApplication creates a new Excel instance and tracks it on the given context's arena.

type Calculation added in v0.7.0

type Calculation int32

Calculation mirrors Excel's `XlCalculation` enum used by Application.Calculation. xlwings exposes the same idea as the strings "automatic" / "manual" / "semiautomatic"; we expose the COM ints directly because xlwings' string form is just a thin wrapper over these.

const (
	CalculationAutomatic     Calculation = -4105 // xlCalculationAutomatic
	CalculationManual        Calculation = -4135 // xlCalculationManual
	CalculationSemiautomatic Calculation = 2     // xlCalculationSemiautomatic
)

type OptionedRange added in v0.7.1

type OptionedRange interface {
	// Value returns the decoded value applying every configured option.
	// xlwings parity: `rng.options(...).value`.
	Value() (interface{}, error)
	// Get decodes the read into the supplied destination pointer. Supported
	// destinations:
	//
	//   - *interface{}    — same as Value().
	//   - *string, *float64, *int, *int64, *bool, *time.Time — scalar reads.
	//   - *[]any          — flat 1-D copy of the read.
	//   - *[][]any        — full 2-D grid.
	//   - *[]MyStruct     — struct-by-header decode (requires Header(true)).
	//
	// Returns an error if the read shape and destination cannot be reconciled.
	Get(dst interface{}) error
	// Err returns the first deferred error captured while building this
	// OptionedRange (e.g. an invalid Expand direction).
	Err() error
}

OptionedRange is the deferred-read view returned by Range.Options(...). It captures the original Range plus a set of conversion options and runs the conversion lazily on Value()/Get().

OptionedRange follows the sugar Chain contract for arena-tracking: the underlying Range is reused as-is, so any IDispatch references stay owned by the parent context.

type Range added in v0.4.0

type Range interface {
	sugar.Chain
	// Value reads the range's value. For a single-cell range it returns the
	// underlying scalar (bool, float64, string, time.Time, …). For a
	// multi-cell range it returns `[][]interface{}` shaped `[row][col]`,
	// mirroring xlwings' `range.value` semantics.
	Value() (interface{}, error)
	// SetValue sets the value for the entire range. Pass a scalar to fill
	// every cell; pass a `[][]interface{}` to write a 2-D block (the slice
	// must match the range's shape).
	SetValue(value interface{}) Range
	// Address returns the cell address as a string (e.g. "$A$1:$B$2").
	Address() (string, error)
	// Formula returns the A1-style formula text.
	Formula() (string, error)
	// SetFormula sets an A1-style formula.
	SetFormula(formula string) Range
	// Formula2 returns the modern dynamic-array formula text (Excel 365+).
	Formula2() (string, error)
	// SetFormula2 sets a dynamic-array formula. Prefer this over SetFormula
	// for code that targets Excel 365's array-spill behavior.
	SetFormula2(formula string) Range
	// NumberFormat returns the Excel number format string (e.g. "0.00").
	NumberFormat() (string, error)
	// SetNumberFormat applies an Excel number format string.
	SetNumberFormat(fmt string) Range

	// Cells returns a single-cell Range relative to this range, 1-based.
	Cells(row, col interface{}) Range
	// Offset shifts the anchor by (rowOffset, colOffset).
	Offset(rowOffset, colOffset int) Range
	// Resize returns a new range of the given shape anchored at this range's
	// top-left cell.
	Resize(rows, cols int) Range
	// Rows returns the rows collection of this range.
	Rows() Range
	// Columns returns the columns collection of this range.
	Columns() Range

	// Row returns the 1-based index of the range's first row.
	Row() (int32, error)
	// Column returns the 1-based index of the range's first column.
	Column() (int32, error)
	// Count returns the number of cells in the range (rows × cols).
	Count() (int32, error)

	// Clear clears values, formulas, and formatting.
	Clear() error
	// ClearContents clears values and formulas but preserves formatting.
	ClearContents() error
	// Delete removes the cells; remaining cells shift up (Excel default).
	Delete() error
	// Copy copies the range to the clipboard (no destination argument).
	Copy() error

	// Merge merges all cells in the range into one.
	Merge() error
	// UnMerge undoes a Merge.
	UnMerge() error
	// MergeCells reports whether all cells in the range are merged.
	MergeCells() (bool, error)

	// AutoFit auto-fits the column width (or row height) for this range.
	AutoFit() error

	// Options is the Go equivalent of xlwings' `Range.options(...)`. It
	// returns an OptionedRange that decodes the range on .Value() / .Get()
	// with the supplied conversion knobs (Scalar/Vector/Grid, Expand,
	// Header, Empty, DateFormat, Convert). See options.go for the full
	// option catalogue.
	Options(opts ...RangeOption) OptionedRange
}

Range is a cell, row, column, or selection of cells — the Go equivalent of xlwings' `Range`.

xlwings reference: https://docs.xlwings.org/en/stable/api/range.html

type RangeOption added in v0.7.1

type RangeOption func(*rangeOptions)

RangeOption is the functional-options type accepted by Range.Options. Each option mutates a private rangeOptions struct; the rangeOptions value is stored on the returned OptionedRange and consumed by Value/Get.

func Convert added in v0.7.1

func Convert(fn func(raw [][]interface{}) (interface{}, error)) RangeOption

Convert installs a caller-supplied function that receives the raw 2-D read (after Empty replacement, before shape forcing or struct decode) and returns the value handed back to Value()/Get(). Mirrors xlwings' `.options(MyConverter, ...)` escape hatch.

When Convert is set, Shape, Header, and struct decode are bypassed — the function owns the projection end-to-end.

func DateFormat added in v0.7.1

func DateFormat(layout string) RangeOption

DateFormat sets a `time.Format` layout used when assigning time.Time values into string struct fields. xlwings hands the layout to Python's `datetime.strftime`; in Go we use the equivalent `time.Format` layout.

If unset, time.Time values are written into string fields via time.Time.String().

func Empty added in v0.7.1

func Empty(value interface{}) RangeOption

Empty replaces nil cells with the provided value during decoding. Mirrors xlwings' `.options(empty=...)`. The replacement is applied after the raw 2-D read but before shape forcing / struct decode.

func Expand added in v0.7.1

func Expand(direction string) RangeOption

Expand auto-grows the range from its anchor (top-left cell) before reading. Supported directions mirror xlwings:

  • "table" — grow down then right until the first empty cell in each direction (xlwings' default for `expand=...`).
  • "down" — grow down only.
  • "right" — grow right only.

An unknown direction defers an error onto the OptionedRange's chain so the caller observes it from .Value() / .Get() / .Err().

func Grid added in v0.7.1

func Grid() RangeOption

Grid is the xlwings `.options(ndim=2)` analogue: always return [][]interface{} (one row per Excel row). Vector2D is a verbose alias.

func Header(on bool) RangeOption

Header treats the first row of the read result as struct field names when decoding into a `*[]SomeStruct` destination. Matches xlwings' `.options(pd.DataFrame, header=1, ...)` flag for the struct case.

When true, the first row is consumed as headers; remaining rows become elements of the destination slice. The default false treats every row as data and requires position-based decoding (not yet implemented — pass true or use Convert for now).

func Scalar added in v0.7.1

func Scalar() RangeOption

Scalar is the xlwings `.options(ndim=0)` analogue: force a single-cell read and return the underlying scalar (or error on a multi-cell range).

func Vector added in v0.7.1

func Vector() RangeOption

Vector is the xlwings `.options(ndim=1)` analogue: force a 1-D slice result. Vector1D is provided as a verbose alias for callers who prefer the explicit dimensionality in the name.

func Vector1D added in v0.7.1

func Vector1D() RangeOption

Vector1D is a verbose alias for Vector(). It exists only to match readers who expect the xlwings-style "1d" suffix.

func Vector2D added in v0.7.1

func Vector2D() RangeOption

Vector2D is a verbose alias for Grid().

type Shape added in v0.7.1

type Shape int

Shape is the dimension forcing knob exposed by xlwings' `.options(ndim=...)`. Scalar / Vector / Grid mirror xlwings' implicit ndim=0/1/2.

const (
	// ShapeAuto leaves the result in its natural xlwings shape: a single
	// scalar for 1×1, a flat `[]interface{}` for 1×N or N×1, and
	// `[][]interface{}` for everything else. This is the default.
	ShapeAuto Shape = iota
	// ShapeScalar forces a 1×1 read. The Value()/Get() call errors out if
	// the underlying range has more than one cell.
	ShapeScalar
	// ShapeVector forces a 1-D slice. `1×N` is read row-wise; `N×1` is read
	// column-wise. Anything else returns an error.
	ShapeVector
	// ShapeGrid forces a `[][]interface{}` result, even for `1×1`, `1×N`,
	// or `N×1` ranges. Equivalent to xlwings' `ndim=2`.
	ShapeGrid
)

type SheetVisibility added in v0.7.0

type SheetVisibility int32

SheetVisibility mirrors Excel's `XlSheetVisibility` enum values used by Worksheet.Visible. xlwings exposes these as the strings "visible", "hidden", "very_hidden"; we expose the COM ints directly.

const (
	SheetVisible    SheetVisibility = -1 // xlSheetVisible
	SheetHidden     SheetVisibility = 0  // xlSheetHidden
	SheetVeryHidden SheetVisibility = 2  // xlSheetVeryHidden
)

type Workbook added in v0.4.0

type Workbook interface {
	sugar.Chain
	// Worksheets returns the collection of all worksheets in the workbook.
	Worksheets() Worksheets
	// Sheets is the xlwings-named alias for Worksheets.
	Sheets() Worksheets
	// ActiveSheet returns the worksheet that is currently active in this
	// workbook.
	ActiveSheet() Worksheet
	// App returns the parent Application that owns this workbook.
	// Equivalent to xlwings' `book.app`.
	App() Application
	// Name returns the workbook's file name (e.g. "Book1.xlsx").
	Name() (string, error)
	// FullName returns the workbook's full path including the file name.
	FullName() (string, error)
	// Path returns the directory of the workbook (without the file name).
	Path() (string, error)
	// Saved reports whether the workbook has unsaved changes (true = clean).
	Saved() (bool, error)
	// SetSaved marks the workbook's modified flag. Set to true to suppress
	// the "Save changes?" prompt on Close.
	SetSaved(v bool) Workbook
	// Activate makes this workbook the active workbook in its application.
	Activate() error
	// Save saves the workbook to its existing path. The workbook must have a
	// file name (use SaveAs for a new file).
	Save() error
	// SaveAs saves the workbook to the given path. Excel infers the file
	// format from the extension.
	SaveAs(path string) error
	// Close closes the workbook. Any unsaved changes are discarded if Saved
	// is true; otherwise Excel may prompt unless DisplayAlerts is false on
	// the parent Application.
	Close() error
}

Workbook is the Go equivalent of xlwings' `Book` — a single Excel workbook.

xlwings reference: https://docs.xlwings.org/en/stable/api/book.html

type Workbooks added in v0.4.0

type Workbooks interface {
	sugar.Chain
	// Add creates a new empty workbook.
	Add() Workbook
	// Open opens an existing workbook by file path. The path must be an
	// absolute path. xlwings reference: `books.open(fullname=...)`.
	Open(path string) Workbook
	// Item returns a specific workbook by index (1-based) or name.
	Item(index interface{}) Workbook
	// Count returns the number of open workbooks. Equivalent to len(books)
	// in xlwings.
	Count() (int32, error)
	// Active returns the currently active workbook in the parent application.
	// Equivalent to xlwings' `books.active`.
	Active() Workbook
}

Workbooks is the Go equivalent of xlwings' `Books` collection — the collection of all open workbooks. xlwings exposes both `app.books` and `xw.books`; we keep the Workbooks name to match the Excel COM type and supply `Application.Books()` as the xlwings-style alias.

xlwings reference: https://docs.xlwings.org/en/stable/api/books.html

type Worksheet added in v0.4.0

type Worksheet interface {
	sugar.Chain
	// Range returns a Range object. Arguments can be "A1", ("A1", "B2"), or
	// any Excel-accepted address form.
	Range(cell1 interface{}, cell2 ...interface{}) Range
	// Cells returns a Range object representing a single cell at
	// (row, col), both 1-based.
	Cells(row, col interface{}) Range
	// UsedRange returns the rectangular range that bounds all cells with
	// content or formatting in the sheet.
	UsedRange() Range
	// Name returns the worksheet's tab name.
	Name() (string, error)
	// SetName renames the worksheet.
	SetName(name string) Worksheet
	// Index returns the 1-based tab index of the worksheet.
	Index() (int32, error)
	// Visible returns the current visibility state.
	Visible() (SheetVisibility, error)
	// SetVisible sets the visibility state. Use SheetVisible / SheetHidden /
	// SheetVeryHidden.
	SetVisible(v SheetVisibility) Worksheet
	// Activate makes this the active worksheet.
	Activate() error
	// Delete removes this worksheet from its workbook. Excel typically
	// prompts unless DisplayAlerts is false on the parent Application.
	Delete() error
	// Clear clears both values and formatting from every cell.
	Clear() error
	// ClearContents clears values and formulas but keeps formatting.
	ClearContents() error
	// AutoFit auto-fits the width of all columns and the height of all rows
	// in UsedRange.
	AutoFit() error
}

Worksheet is a single worksheet — the Go equivalent of xlwings' `Sheet`.

xlwings reference: https://docs.xlwings.org/en/stable/api/sheet.html

type Worksheets added in v0.4.0

type Worksheets interface {
	sugar.Chain
	// Item returns a worksheet by 1-based index or by name.
	Item(index interface{}) Worksheet
	// Add inserts a new worksheet. With no arguments the new sheet is added
	// before the currently active sheet; pass options for finer placement.
	// xlwings reference: `sheets.add(name=None, before=None, after=None)`.
	Add(opts ...AddOption) Worksheet
	// Count returns the number of worksheets.
	Count() (int32, error)
	// Active returns the currently active worksheet in the parent workbook.
	Active() Worksheet
}

Worksheets is the collection of worksheets in a workbook — the Go equivalent of xlwings' `sheets`.

xlwings reference: https://docs.xlwings.org/en/stable/api/sheets.html

Jump to

Keyboard shortcuts

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