tealeg/xlsx

repository·master·Indexed 26 days ago

https://github.com/tealeg/xlsx

A Go library for reading and writing Microsoft Excel XML files, providing a simplified interface for the Office Open XML format. It includes features for managing cell values, types, and formatting, handling dates and times, adding hyperlinks, and implementing custom CellStore interfaces for memory-efficient processing of large spreadsheets. The library also supports column range management, data validation rules, and dropdown list creation.

Tokens
10.8K
Snippets
15
Records
100
Agent score
91%

What's inside tealeg/xlsx

  1. Install and import the xlsx package

    master

    To use the xlsx package in your Go project, import it using the v3 module path. If you are using Go modules, ensure your go.mod file includes the requirement for the v3 version.

    It is highly recommended to use at least version 3.2.0 to access row and cell coordinate information.

    import "github.com/tealeg/xlsx/v3"
    # In your go.mod
    require github.com/tealeg/xlsx/v3 v3.2.0
  2. Migrate to XLSX v4 on Codeberg

    master
    The XLSX library has migrated from GitHub to Codeberg. Version 4 is the current active version. The GitHub repository (v3) is no longer receiving further support or maintenance. To use the latest version or contribute, migrate to the Codeberg repository.
  3. Understanding XLSX version differences

    master

    The library has undergone several breaking changes across major versions:

    • v1.x.x: Legacy maintenance branch. Use only if you have existing code that cannot be updated.
    • v2.x.x: Introduced breaking changes to Col elements and DataValidation to better align with the XLSX format. Note that v2.0.0 is incompatible with Go Modules; use v2.0.1 or later for Go Modules support.
    • v3.x.x: Introduced breaking changes where methods returning an xlsx.File struct now accept zero or more xlsx.FileOption functions as final arguments. This version replaced ...WithRowLimit variants with xlsx.RowLimit and added support for custom backing stores. StreamFileBuilder was removed.
    • v4.x.x: The current version, hosted on Codeberg.
  4. Work with rows

    master

    Rows are 0-indexed. Use sh.Row(index int) to get a specific row. Use sh.MaxRow to determine the total number of rows (note: MaxRow is 1-based, e.g., if there are 4 rows, MaxRow is 4).

    Row Operations:

    • Add at end: sh.AddRow()
    • Add at index: sh.AddRowAtIndex(index int) (returns error if index is out of bounds).
    • Remove at index: sh.RemoveRowAtIndex(index int).
    • Iterate: sh.ForEachRow(func(r *xlsx.Row) error).
    • Get Coordinates: Starting with v3.2.0, use row.GetCoordinate() to get the zero-based row index.
  5. Format and style cells

    master

    Cells can be styled using the xlsx.Style struct. It is best practice to create a style once and reuse it across multiple cells.

    Number and Date Formats:

    • Use c.SetFormat(formatString) or c.NumFmt = formatString to set numeric/date formats.
    • Use c.SetFloatWithFormat(val, format) for a single-call approach.

    Applying Styles:

    1. Create a style: myStyle := xlsx.NewStyle().
    2. Configure fields: myStyle.Font.Bold = true, myStyle.Alignment.Horizontal = "right", etc.
    3. Set application flags: myStyle.ApplyFont = true, myStyle.ApplyAlignment = true.
    4. Assign to cell: cell.SetStyle(myStyle).

    Retrieving Styles:

    • cell.GetStyle() returns a pointer to the Style struct.
    // Create and configure a style
    myStyle := xlsx.NewStyle()
    myStyle.Alignment.Horizontal = "right"
    myStyle.Fill.FgColor = "FFFFFF00"
    myStyle.Fill.PatternType = "solid"
    myStyle.Font.Name = "Georgia"
    myStyle.Font.Size = 11
    myStyle.Font.Bold = true
    myStyle.ApplyAlignment = true
    myStyle.ApplyFill = true
    myStyle.ApplyFont = true
    
    // Apply to cell
    cell.SetStyle(myStyle)
    
    // Set numeric format
    cell.SetFormat("#0.00;[RED]-#0.00")
  6. Configure column properties

    master

    In v3, columns are defined via xlsx.Col structs which can represent a range of columns. You can associate these definitions with a sheet using sh.SetColParameters(col).

    Column Width: Width is expressed as the number of characters of the maximum digit width (0-9) that fit in a cell.

    • Set a range: sh.SetColWidth(min, max, width).
    • Set via Col struct: newColumn.SetWidth(width).

    Column Range Example: Use xlsx.NewColForRange(min, max) to create a column definition for a specific range (e.g., columns A through E).

  7. Access and create worksheets

    master

    Worksheets can be accessed via the Sheets slice or the Sheet map (where the key is the sheet name). Always check if a sheet exists in the map to avoid nil pointer errors.

    To add a new sheet, use AddSheet(name string). To append an existing *xlsx.Sheet struct, use AppendSheet(sheet *xlsx.Sheet, name string).

    Sheet Naming Rules:

    • Minimum length: 1 character.
    • Maximum length: 31 characters.
    • Disallowed characters: : / ? * [ ]
    // Access a specific sheet by name
    sheetName := "Sample"
    sh, ok := wb.Sheet[sheetName]
    if !ok {
        fmt.Println("Sheet does not exist")
        return
    }
    
    // Create a new sheet
    sh, err := wb.AddSheet("My New Sheet")
    
    // Append an existing sheet struct
    sh, err := wb.AppendSheet(newSheet, "A new sheet")
  8. Export workbook as bytes

    master

    To get the workbook content as a byte stream (e.g., for web responses) without writing to disk, use the Write() method on xlsx.File with a bytes.Buffer and a bufio.Writer.

    file := xlsx.NewFile()
    // ... perform operations ...
    
    var b bytes.Buffer
    writer := bufio.NewWriter(&b)
    file.Write(writer)
    
    theBytes := b.Bytes()
  9. Open or create xlsx files

    master

    Use xlsx.OpenFile() to open an existing .xlsx file and xlsx.NewFile() to create a new, empty workbook.

    To access all sheets in a workbook, iterate over the Sheets field (a slice of *xlsx.Sheet).

    // open an existing file
    wb, err := xlsx.OpenFile("../samplefile.xlsx")
    if err != nil {
        panic(err)
    }
    
    // show all the sheets in the workbook
    for i, sh := range wb.Sheets {
        fmt.Println(i, sh.Name)
    }
    
    // create a new, empty xlsx-File
    wb := xlsx.NewFile()
  10. Work with cells

    master

    Cells can be accessed from a Sheet or a Row.

    Accessing Cells:

    • sh.Cell(row, col int): Returns a cell at specific coordinates (0-indexed). Creates the cell if it doesn't exist.
    • row.GetCell(colIdx int): Returns a cell at the given column index. Creates the cell if it doesn't exist.
    • row.AddCell(): Appends a new cell to the end of the row.

    Getting Values:

    • c.Value(): Returns a string.
    • c.FormattedValue(): Returns the value with formatting applied.
    • c.String(): Returns the cell's value as a string.
    • c.Formula(): Returns the formula string (empty if no formula).
    • c.Int(), c.Float(), c.Bool(): Returns typed values.

    Coordinate Helpers:

    • ColIndexToLetters(index int)
    • ColLettersToIndex(colLetter string)
    • GetCoordsFromCellIDString(cellAddr string)
    • GetCellIDStringFromCoords(x, y int)
  11. Iterate over cells in a Row

    master

    Use ForEachCell to iterate through all defined cells in a row. You can provide CellVisitorOption to modify the iteration behavior.

    • ForEachCell(cvf CellVisitorFunc, option ...CellVisitorOption): Executes the provided function for each cell.
    • SkipEmptyCells: An option that, when passed, causes the iterator to skip over nil/empty cells.