Documentation
¶
Overview ¶
Package xlsxlite is a lightweight, memory-efficient XLSX read/write library.
Unlike DOM-based libraries that load entire worksheet XML into memory, xlsxlite uses streaming XML parsing (encoding/xml.Decoder) for reading and streaming XML writing for output. This keeps memory usage proportional to a single row rather than the entire file, enabling processing of arbitrarily large spreadsheets.
Design principles:
- Zero external dependencies (stdlib only)
- Streaming read via row iterator (cursor pattern)
- Streaming write via row-by-row flush
- Shared string table with chunked/indexed access for reads
- Style support: fonts, fills, borders, alignment, number formats
- Merge cells, column widths, row heights
- No formula engine, no charts, no images (keeps it lean)
Index ¶
- Constants
- func CellRef(col, row int) string
- func ColIndexToLetter(col int) string
- func ExcelSerialToTime(serial float64) time.Time
- func LetterToColIndex(letters string) int
- func ParseCellRef(ref string) (col, row int, err error)
- func RangeRef(startCol, startRow, endCol, endRow int) string
- func TimeToExcelSerial(t time.Time) float64
- type Alignment
- type Border
- type BorderEdge
- type Cell
- type CellType
- type Fill
- type Font
- type MergeCell
- type Reader
- type Row
- type RowIterator
- type SheetConfig
- type SheetWriter
- type Style
- type StyleSheet
- type Writer
Constants ¶
const ( // MaxColumns is the maximum number of columns supported (Excel's limit: XFD = 16384). MaxColumns = 16384 MaxSharedStrings = 10_000_000 // MaxDecompressedSize is the maximum decompressed size of any single zip entry (256 MB). MaxDecompressedSize = 256 << 20 // MaxGCSDownloadSize is the maximum size for GCS file downloads (512 MB). MaxGCSDownloadSize = 512 << 20 )
Variables ¶
This section is empty.
Functions ¶
func ColIndexToLetter ¶
ColIndexToLetter converts a 0-based column index to Excel column letters. 0 → "A", 25 → "Z", 26 → "AA", etc.
func ExcelSerialToTime ¶
ExcelSerialToTime converts an Excel serial date number back to time.Time. Used internally by the reader to convert numeric cells with date styles.
func LetterToColIndex ¶
LetterToColIndex converts Excel column letters to a 0-based column index. "A" → 0, "Z" → 25, "AA" → 26, etc.
func ParseCellRef ¶
ParseCellRef parses a cell reference like "A1" into a 0-based column index and 1-based row number. Returns an error for invalid references.
func RangeRef ¶
RangeRef creates a range reference like "A1:D5" from 0-based column indices and 1-based row numbers.
func TimeToExcelSerial ¶
TimeToExcelSerial converts a time.Time to an Excel serial date number. The serial number represents days since December 30, 1899 (Excel's epoch).
Types ¶
type Alignment ¶
type Alignment struct {
Horizontal string // "left", "center", "right", "fill", "justify"
Vertical string // "top", "center", "bottom"
WrapText bool
}
Alignment describes cell alignment.
type Border ¶
type Border struct {
Left BorderEdge
Right BorderEdge
Top BorderEdge
Bottom BorderEdge
}
Border describes all four borders of a cell.
type BorderEdge ¶
type BorderEdge struct {
Style string // "thin", "medium", "thick", "dashed", etc.
Color string // ARGB hex
}
BorderEdge describes one edge of a cell border.
type Cell ¶
type Cell struct {
Value any // string, float64, bool, time.Time, or nil
Type CellType
StyleID int // index into the styles table; 0 = default
}
Cell represents a single cell value with optional style. The Value field holds the Go value (string, float64, int, int64, float32, bool, time.Time, or nil). The Type field must match the value's kind. Use the cell constructors (StringCell, NumberCell, etc.) or MakeRow for convenience.
func DateCell ¶
DateCell creates a date cell with the given style. The styleID should reference a style with a date NumberFormat (e.g. "yyyy-mm-dd") so Excel displays it as a date instead of a raw serial number.
func EmptyCell ¶
func EmptyCell() Cell
EmptyCell returns an empty cell (useful for padding in rows).
func NumberCell ¶
NumberCell creates a numeric cell from a float64 value.
func StringCell ¶
StringCell creates a string cell. The value is stored as a shared string in the XLSX file. No type coercion is performed, so leading zeros and numeric-looking strings are preserved as-is.
func StyledCell ¶
StyledCell creates a cell with a specific style. The cell type is auto-detected from the Go value type: string → CellTypeString, float64/float32/int/int64 → CellTypeNumber, bool → CellTypeBool, anything else → CellTypeEmpty.
type CellType ¶
type CellType int
CellType represents the data type of a cell.
const ( CellTypeEmpty CellType = iota // empty or nil cell CellTypeString // string value (stored as shared string) CellTypeNumber // numeric value (float64, int, int64, or float32) CellTypeBool // boolean value CellTypeDate // date/time value (stored as Excel serial number) CellTypeInlineString // inline string (not shared) )
type Fill ¶
type Fill struct {
Type string // "pattern" or "none"
Pattern string // "solid", "gray125", etc.
FgColor string // ARGB hex
BgColor string // ARGB hex
}
Fill describes a cell fill/background. Set Type to "pattern" and Pattern to "solid" for a solid color fill. FgColor and BgColor are ARGB hex strings.
type Font ¶
type Font struct {
Name string
Size float64
Bold bool
Italic bool
Underline bool
Color string // ARGB hex, e.g. "FF000000"
}
Font describes a font style. All fields are optional; zero values are omitted from the output. Color is an ARGB hex string (e.g. "FF000000" for black).
type MergeCell ¶
type MergeCell struct {
StartCol int // 0-based column
StartRow int // 1-based row
EndCol int // 0-based column
EndRow int // 1-based row
}
MergeCell represents a merged cell range. Columns are 0-based, rows are 1-based (matching Excel conventions).
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader reads XLSX files using streaming XML parsing. The shared string table is loaded into memory (unavoidable for random access), but worksheet rows are read one-at-a-time via a streaming XML decoder.
func OpenFile ¶
OpenFile opens an XLSX file from disk for streaming reading. The caller must call Reader.Close when done to release the underlying file handle.
func OpenReader ¶
OpenReader opens an XLSX file for streaming reading from an io.ReaderAt (e.g. *os.File, *bytes.Reader). It parses the workbook structure, loads the shared string table, and reads style definitions. Use OpenFile for a simpler file-based API.
func (*Reader) Close ¶
Close releases any resources held by the Reader. If the Reader was created via OpenFile, this closes the underlying file.
func (*Reader) OpenSheet ¶
func (r *Reader) OpenSheet(name string) (*RowIterator, error)
OpenSheet returns a RowIterator for the sheet with the given name. The caller must call RowIterator.Close when done reading.
func (*Reader) OpenSheetByIndex ¶
func (r *Reader) OpenSheetByIndex(index int) (*RowIterator, error)
OpenSheetByIndex returns a RowIterator for the sheet at the given 0-based index. The caller must call RowIterator.Close when done reading.
func (*Reader) SetCloser ¶ added in v0.1.3
SetCloser sets the closer that will be called when Reader.Close is invoked. This is used by helpers (e.g. gcs.OpenFileLowMem) to attach cleanup logic such as deleting temporary files.
func (*Reader) SheetCount ¶
SheetCount returns the number of sheets.
func (*Reader) SheetNames ¶
SheetNames returns the names of all sheets in workbook order.
type Row ¶
type Row struct {
Cells []Cell
Height float64 // custom row height; 0 = default
RowIndex int // 1-based row number
}
Row represents a single row of cells. Set RowIndex to override the auto-incremented row number (1-based). Set Height to apply a custom row height in points.
func MakeRow ¶
MakeRow is a convenience to create a Row from a variadic list of values. Accepted types: string, float64, float32, int, int64, bool, Cell, and nil. Strings are stored as shared strings with no type coercion (leading zeros are preserved). Any other type is converted to a string via fmt.Sprintf.
type RowIterator ¶
type RowIterator struct {
// contains filtered or unexported fields
}
RowIterator streams rows from a worksheet one at a time. Use Next to advance, Row to get the current row, and Err to check for errors. The caller must call Close when done to release the underlying zip entry reader.
func (*RowIterator) Close ¶
func (it *RowIterator) Close() error
Close releases resources held by the iterator. It is safe to call Close multiple times. After Close, Next will always return false.
func (*RowIterator) Err ¶
func (it *RowIterator) Err() error
Err returns the first error encountered during iteration, or nil if iteration completed successfully.
func (*RowIterator) Next ¶
func (it *RowIterator) Next() bool
Next advances to the next row. Returns false when there are no more rows or an error occurred. After Next returns false, call Err to check for errors.
func (*RowIterator) Row ¶
func (it *RowIterator) Row() *Row
Row returns the current row. Only valid after Next() returns true.
type SheetConfig ¶
type SheetConfig struct {
Name string
ColWidths map[int]float64 // 0-based col index → width
MergeCells []MergeCell
FreezeRow int // freeze panes: first N rows
FreezeCol int // freeze panes: first N cols
}
SheetConfig holds configuration for a worksheet. Pass this to Writer.NewSheet to create a new sheet with the given settings.
type SheetWriter ¶
type SheetWriter struct {
// contains filtered or unexported fields
}
SheetWriter writes rows to a single worksheet in streaming fashion. Rows are flushed immediately on WriteRow, so memory usage is O(1) per row.
func (*SheetWriter) Close ¶
func (sw *SheetWriter) Close() error
Close finalizes the sheet XML (closes sheetData, writes merge cells, etc.). Must be called before creating another sheet or closing the Writer.
func (*SheetWriter) WriteRow ¶
func (sw *SheetWriter) WriteRow(row Row) error
WriteRow writes a single row and immediately flushes it to the zip entry. Rows must be written in sequential order. If Row.RowIndex is set (> 0), it overrides the auto-incremented row number, allowing gaps between rows.
type Style ¶
type Style struct {
Font *Font
Fill *Fill
Border *Border
Alignment *Alignment
NumberFormat string // custom format string, e.g. "yyyy-mm-dd"
}
Style combines font, fill, border, alignment and number format. All fields are optional (nil pointers and empty strings are omitted). Register styles via StyleSheet.AddStyle before writing rows.
type StyleSheet ¶
type StyleSheet struct {
// contains filtered or unexported fields
}
StyleSheet manages Excel styles and generates styles.xml content. Styles in XLSX are composed of 4 independent tables (fonts, fills, borders, numFmts) and a cross-reference table (cellXfs) that combines indices from each.
func NewStyleSheet ¶
func NewStyleSheet() *StyleSheet
NewStyleSheet creates a StyleSheet with the defaults required by Excel: one font (Calibri 11), two fills (none + gray125), one border (empty), and one default cell format. This is called automatically by NewWriter.
func (*StyleSheet) AddStyle ¶
func (ss *StyleSheet) AddStyle(s Style) int
AddStyle registers a Style and returns its 0-based index for use in Cell.StyleID. Identical styles are deduplicated — calling AddStyle with the same parameters multiple times returns the same index.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer creates XLSX files using streaming writes. Rows are flushed to the underlying zip entry immediately, so memory usage stays proportional to a single row regardless of file size.
func CreateFile ¶
CreateFile creates a new XLSX file on disk for streaming writing. Returns the Writer and the underlying os.File. Call Writer.Close() first to finalize the XLSX package, then close the file.
func NewWriter ¶
NewWriter creates a new streaming XLSX writer that writes to w. Typical workflow: register styles via StyleSheet(), create sheets via NewSheet(), write rows via SheetWriter.WriteRow(), then call Close() to finalize.
func (*Writer) Close ¶
Close finalizes the entire XLSX package by writing styles, shared strings, workbook, content types, and relationships, then closes the underlying zip writer. All SheetWriters must be closed before calling this method.
func (*Writer) NewSheet ¶
func (w *Writer) NewSheet(config SheetConfig) (*SheetWriter, error)
NewSheet begins a new worksheet. You must call SheetWriter.Close() when done writing rows to this sheet before starting another.
func (*Writer) StyleSheet ¶
func (w *Writer) StyleSheet() *StyleSheet
StyleSheet returns the style sheet for registering styles. Styles must be registered before writing rows that reference them.