### Iterate over cells in a row Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc This example demonstrates how to iterate over each cell in a row using `ForEachCell` and a visitor function. It prints the formatted value of each cell or any errors encountered. ```go package main import ( "errors" "fmt" "github.com/tealeg/xlsx/v3" ) func cellVisitor(c *xlsx.Cell) error { value, err := c.FormattedValue() if err != nil { fmt.Println(err.Error()) } else { fmt.Println("Cell value:", value) } return err } func rowVisitor(r *xlsx.Row) error { return r.ForEachCell(cellVisitor) } func rowStuff() { filename := "samplefile.xlsx" wb, err := xlsx.OpenFile(filename) if err != nil { panic(err) } sh, ok := wb.Sheet["Sample"] if !ok { panic(errors.New("Sheet not found")) } fmt.Println("Max row is", sh.MaxRow) ``` -------------------------------- ### Get Workbook Contents as Bytes Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Demonstrates how to get the xlsx file content as a byte buffer instead of writing it directly to disk. This is useful for handling the file data in memory. ```go file := xlsx.NewFile() /* do something with the File... */ var b bytes.Buffer writer := bufio.NewWriter(&b) file.Write(writer) theBytes := b.Bytes() /* now you have the byte stream in b. if you use some other type that fulfills thr Writer interface, go ahead. */ ``` -------------------------------- ### Set and Get Date/Time with Options Source: https://context7.com/tealeg/xlsx/llms.txt Parses a numeric Excel date cell into `time.Time` using `Cell.GetTime(date1904 bool)`. `Cell.IsTime()` checks if the cell format is date/time. `SetDateWithOptions` allows specifying timezone and Excel display format. ```go package main import ( "fmt" "log" "time" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Dates") loc, _ := time.LoadLocation("America/New_York") t := time.Date(2024, 3, 15, 9, 30, 0, 0, loc) row := s.AddRow() c := row.AddCell() c.SetDateWithOptions(t, xlsx.DateTimeOptions{ Location: loc, ExcelTimeFormat: "YYYY-MM-DD HH:MM:SS", }) if err := f.Save("dates.xlsx"); err != nil { log.Fatal(err) } // Read back f2, _ := xlsx.OpenFile("dates.xlsx") cell, _ := f2.Sheets[0].Cell(0, 0) fmt.Println("IsTime:", cell.IsTime()) t2, err := cell.GetTime(false) if err != nil { log.Fatal(err) } fmt.Println("Parsed:", t2.Format(time.RFC3339)) } ``` -------------------------------- ### Retrieve and Display Cell Style Information Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Read style properties from a specific cell in an Excel file using GetStyle(). This example demonstrates retrieving and printing the font name, size, horizontal alignment, foreground color, and background color of a cell. ```go package main import ( "errors" "fmt" "github.com/tealeg/xlsx/v3" ) func MAIN() { filename := "samplefile.xlsx" wb, _ := xlsx.OpenFile(filename) sh := wb.Sheet["Styles"] cell, _ := sh.Cell(0, 1) style := cell.GetStyle() fmt.Println("Cell value:", cell.String()) fmt.Println("Font:", style.Font.Name) fmt.Println("Size:", style.Font.Size) fmt.Println("H-Align:", style.Alignment.Horizontal) fmt.Println("ForeColor:", style.Fill.FgColor) fmt.Println("BackColor:", style.Fill.BgColor) } ``` -------------------------------- ### Get Row by Index Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Retrieves a specific row from a sheet using its 0-based index. Handles potential errors during retrieval. ```go // sh is a reference to a sheet, see above row, err := sh.Row(1) if err != nil { panic(err) } // let's do something with the row ... fmt.Println(row) ``` -------------------------------- ### Create a New XLSX File and Add Data Source: https://context7.com/tealeg/xlsx/llms.txt Create a new workbook using `xlsx.NewFile`, add sheets with `File.AddSheet`, and populate them with rows and cells using `Sheet.AddRow` and `Row.AddCell`. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() sheet, err := f.AddSheet("Inventory") if err != nil { log.Fatal(err) } // Header row header := sheet.AddRow() header.AddCell().SetString("Product") header.AddCell().SetString("Qty") header.AddCell().SetString("Price") // Data rows for _, item := range []struct { name string qty int price float64 }{ {"Widget A", 100, 9.99}, {"Widget B", 250, 4.49}, } { row := sheet.AddRow() row.AddCell().SetString(item.name) row.AddCell().SetInt(item.qty) row.AddCell().SetFloatWithFormat(item.price, "#,##0.00") } if err := f.Save("inventory.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Open XLSX from Binary Data or io.ReaderAt in Go Source: https://context7.com/tealeg/xlsx/llms.txt Demonstrates opening XLSX files from a byte slice using `xlsx.OpenBinary` and from an `io.ReaderAt` (like an `*os.File`) using `xlsx.OpenReaderAt`. Useful for files obtained from network responses or embedded resources. ```Go package main import ( "log" "os" xlsx "github.com/tealeg/xlsx/v3" ) func main() { // From byte slice bs, err := os.ReadFile("data.xlsx") if err != nil { log.Fatal(err) } f, err := xlsx.OpenBinary(bs) if err != nil { log.Fatalf("OpenBinary: %v", err) } _ = f // From io.ReaderAt (e.g. *os.File implements io.ReaderAt) fh, err := os.Open("data.xlsx") if err != nil { log.Fatal(err) } defer fh.Close() info, _ := fh.Stat() f2, err := xlsx.OpenReaderAt(fh, info.Size()) if err != nil { log.Fatalf("OpenReaderAt: %v", err) } _ = f2 } ``` -------------------------------- ### Open and Read XLSX File in Go Source: https://context7.com/tealeg/xlsx/llms.txt Opens an XLSX file from disk and iterates through its sheets, rows, and cells to print formatted values. Handles potential errors during file opening and row/cell iteration. Uses `xlsx.SkipEmptyRows` to ignore empty rows. ```Go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f, err := xlsx.OpenFile("report.xlsx") if err != nil { log.Fatalf("OpenFile: %v", err) } for _, sheet := range f.Sheets { fmt.Printf("=== Sheet: %s ===\n", sheet.Name) err := sheet.ForEachRow(func(row *xlsx.Row) error { return row.ForEachCell(func(cell *xlsx.Cell) error { val, err := cell.FormattedValue() if err != nil { return err } fmt.Printf("[%s] ", val) return nil }) }, xlsx.SkipEmptyRows) if err != nil { log.Fatalf("ForEachRow: %v", err) } fmt.Println() } } ``` -------------------------------- ### Customize and Apply xlsx Style Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc After creating a new style, customize its properties such as alignment, fill color, font name, size, and boldness. Then, apply these customizations by setting the relevant Apply flags (e.g., ApplyAlignment, ApplyFill, ApplyFont). ```go 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 ``` -------------------------------- ### Create a new xlsx file Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Use the NewFile function to create a new, empty xlsx file. This returns a pointer to an xlsx.File struct. ```go wb := xlsx.NewFile() ``` -------------------------------- ### Create a New xlsx Style Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Initialize a new, empty style object using xlsx.NewStyle(). This function returns a pointer to a Style struct that can then be customized. ```go myStyle := xlsx.NewStyle() ``` -------------------------------- ### Import the tealeg/xlsx package Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Use this import statement to include the package in your Go project. If using go modules, ensure your go.mod file has a require line for the package. ```go import "github.com/tealeg/xlsx/v3" ``` ```go require github.com/tealeg/xlsx/v3 v3.2.0 ``` -------------------------------- ### Style Columns and Set Width Source: https://context7.com/tealeg/xlsx/llms.txt Creates column definitions for a range and applies styles, width, or hidden state. Use `NewColForRange` to define the column span and `SetColParameters` to apply settings to the sheet. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Styled Cols") // Make column 1 wide and bold-header-colored col := xlsx.NewColForRange(1, 1) col.SetWidth(20) headerStyle := xlsx.NewStyle() headerStyle.Fill = xlsx.Fill{ PatternType: xlsx.Solid_Cell_Fill, FgColor: xlsx.RGB_Dark_Green, } headerStyle.Font = xlsx.Font{Color: xlsx.RGB_White, Bold: true, Size: 12} headerStyle.ApplyFill = true headerStyle.ApplyFont = true col.SetStyle(headerStyle) s.SetColParameters(col) // Hide columns 3-5 hidden := xlsx.NewColForRange(3, 5) h := true hidden.Hidden = &h s.SetColParameters(hidden) row := s.AddRow() row.AddCell().SetString("Visible") row.AddCell().SetString("Visible 2") row.AddCell().SetString("Hidden") if err := f.Save("col_style.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create and Set Column Parameters Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Creates a column definition for a range of worksheet columns, sets its width, assigns a style, and associates it with the sheet. Cells in columns A through E will inherit these properties. ```go // creating a column that relates to worksheet columns A thru E (index 1 to 5) newColumn := NewColForRange(1,5) newColumn.SetWidth(12.5) // we defined a style above, so let's assign this style to all cells of the column newColumn.SetStyle(myStyle) // now associate the sheet with this column sh.SetColParameters(newColumn) ``` -------------------------------- ### Open an existing xlsx file Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Use the OpenFile function to load an existing xlsx file. Ensure you handle potential errors during file opening. ```go // open an existing file wb, err := xlsx.OpenFile("../samplefile.xlsx") if err != nil { panic(err) } // wb now contains a reference to the workbook // show all the sheets in the workbook fmt.Println("Sheets in this file:") for i, sh := range wb.Sheets { fmt.Println(i, sh.Name) } fmt.Println("----") ``` -------------------------------- ### Row and Column Grouping in xlsx Source: https://context7.com/tealeg/xlsx/llms.txt Demonstrates how to create collapsible row and column groups in Excel using outline levels. Rows can be assigned an outline level, and columns can be grouped within a specified range. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Outline") // Summary row (level 0) s.AddRow().AddCell().SetString("Total") // Detail rows (level 1 — collapsible under Total) for _, item := range []string{"Item A", "Item B", "Item C"} { r := s.AddRow() r.SetOutlineLevel(1) r.AddCell().SetString(item) } // Group columns 2-3 at outline level 1 s.SetOutlineLevel(2, 3, 1) if err := f.Save("outline.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Row Height Setting Source: https://context7.com/tealeg/xlsx/llms.txt Shows how to set the height of a row using either PostScript points (`SetHeight`) or centimetres (`SetHeightCM`). ```APIDOC ## Row.SetHeight / Row.SetHeightCM `Row.SetHeight(pt)` sets a row's height in PostScript points. `Row.SetHeightCM(cm)` accepts centimetres and converts automatically. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Heights") // Tall header row (40pt ≈ 53px) header := s.AddRow() header.SetHeight(40) header.AddCell().SetString("Header") // 1 cm data rows for i := 0; i < 5; i++ { row := s.AddRow() row.SetHeightCM(1.0) row.AddCell().SetInt(i + 1) } if err := f.Save("heights.xlsx"); err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Configure Freeze Panes in Go Source: https://github.com/tealeg/xlsx/wiki/FreezePanes Use this code to set up frozen panes in an Excel sheet. Configure XSplit for rows, YSplit for columns, and TopLeftCell to define the visible area after freezing. Ensure the SheetViews are correctly assigned to the sheet. ```go pane := xlsx.Pane{ XSplit: 1, // lock rows YSplit: 1, // lock columns TopLeftCell: "B2", // Cell shown in the scrollable area ActivePane: "topRight", State: "frozen", } sheetView := xlsx.SheetView{Pane: &pane} // Set the SheetViews of an existing xlsx.Sheet sheet.SheetViews = []xlsx.SheetView{sheetView} ``` -------------------------------- ### Add, Insert, and Remove Rows in xlsx Source: https://context7.com/tealeg/xlsx/llms.txt Demonstrates adding rows to the end, inserting rows at a specific index, and removing rows by index. Ensure correct error handling for operations. ```go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Rows") for _, name := range []string{"Alice", "Charlie", "Dave"} { r := s.AddRow() r.AddCell().SetString(name) } // Insert "Bob" at index 1 (between Alice and Charlie) inserted, err := s.AddRowAtIndex(1) if err != nil { log.Fatal(err) } inserted.AddCell().SetString("Bob") // Remove Dave (now at index 3) if err := s.RemoveRowAtIndex(3); err != nil { log.Fatal(err) } s.ForEachRow(func(row *xlsx.Row) error { cell := row.GetCell(0) fmt.Println(cell.String()) // Alice, Bob, Charlie return nil }) } ``` -------------------------------- ### Apply Cell Styling Source: https://context7.com/tealeg/xlsx/llms.txt Configure font, fill, border, and alignment properties using xlsx.NewStyle() and apply them to a cell with cell.SetStyle(style). ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Styled") row := s.AddRow() cell := row.AddCell() cell.SetString("IMPORTANT") style := xlsx.NewStyle() style.Font = xlsx.Font{ Size: 14, Name: "Arial", Bold: true, Color: xlsx.RGB_Dark_Red, // "FF9C0006" } style.Fill = xlsx.Fill{ PatternType: xlsx.Solid_Cell_Fill, FgColor: xlsx.RGB_Light_Red, // "FFFFC7CE" } style.Border = *xlsx.NewBorder("thin", "thin", "thin", "thin") style.Alignment = xlsx.Alignment{ Horizontal: "center", Vertical: "center", WrapText: true, } style.ApplyFont = true style.ApplyFill = true style.ApplyBorder = true style.ApplyAlignment = true cell.SetStyle(style) if err := f.Save("styled.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Configure XLSX File Reading with Options in Go Source: https://context7.com/tealeg/xlsx/llms.txt Utilizes `FileOption` functions like `RowLimit`, `ColLimit`, and `ValueOnly` when opening XLSX files to control the reading behavior. `ValueOnly` can save memory by skipping null cells. ```Go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { // Read only the first 100 rows and 10 columns of each sheet f, err := xlsx.OpenFile("huge.xlsx", xlsx.RowLimit(100), xlsx.ColLimit(10), xlsx.ValueOnly(), // skip null cells to save memory ) if err != nil { log.Fatal(err) } sheet := f.Sheets[0] fmt.Printf("Rows loaded: %d (max 100)\n", sheet.MaxRow) fmt.Printf("Cols loaded: %d (max 10)\n", sheet.MaxCol) } ``` -------------------------------- ### Read Cell Content and Formula Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Demonstrates how to retrieve a cell's formatted value, string representation, and formula. Use this to distinguish between numeric cells and cells containing formulas. ```go // let sh be a reference to a xlsx.Sheet // get the Cell in D1, which is row 0, col 3 theCell, err := sh.Cell(0, 3) if err != nil { panic(err) } // we got a cell, but what's in it? fv, err := theCell.FormattedValue() if err != nil { panic(err) } fmt.Println("Numeric cell?:", theCell.Type() == xlsx.CellTypeNumeric) fmt.Println("String:", theCell.String()) fmt.Println("Formatted:", fv) fmt.Println("Formula:", theCell.Formula()) ``` -------------------------------- ### Set Column Widths Source: https://context7.com/tealeg/xlsx/llms.txt Use Sheet.SetColWidth(min, max, width) for explicit widths or Sheet.SetColAutoWidth(colIndex, widthFunc) to auto-fit column widths based on content. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Columns") header := s.AddRow() header.AddCell().SetString("Name") header.AddCell().SetString("Email Address") header.AddCell().SetString("Score") s.AddRow().AddCell().SetString("Alice Johnson") s.AddRow().AddCell().SetString("Bob") // Set explicit width for column 3 (Score) s.SetColWidth(3, 3, 10) // Auto-fit column 1 (Name) using default scale if err := s.SetColAutoWidth(1, xlsx.DefaultAutoWidth); err != nil { log.Fatal(err) } if err := f.Save("columns.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Iterating Rows with Options Source: https://context7.com/tealeg/xlsx/llms.txt Demonstrates using `Sheet.ForEachRow` to iterate over rows, with an option to skip empty rows by passing `xlsx.SkipEmptyRows`. ```APIDOC ## Sheet.ForEachRow with SkipEmptyRows `Sheet.ForEachRow` iterates rows sequentially, calling your `RowVisitor` for each. Pass `xlsx.SkipEmptyRows` to skip rows with no cell data. ```go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f, err := xlsx.OpenFile("sparse.xlsx") if err != nil { log.Fatal(err) } sheet := f.Sheets[0] err = sheet.ForEachRow(func(row *xlsx.Row) error { var vals []string row.ForEachCell(func(cell *xlsx.Cell) error { v, _ := cell.FormattedValue() vals = append(vals, v) return nil }, xlsx.SkipEmptyCells) fmt.Printf("Row %d: %v\n", row.GetCoordinate(), vals) return nil }, xlsx.SkipEmptyRows) if err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Row and Column Grouping Source: https://context7.com/tealeg/xlsx/llms.txt Illustrates how to group rows and columns for collapsible outlines in Excel using `Row.SetOutlineLevel` and `Sheet.SetOutlineLevel`. ```APIDOC ## Row.SetOutlineLevel / Sheet.SetOutlineLevel — Row/Column Grouping `Row.SetOutlineLevel(level)` and `Sheet.SetOutlineLevel(minCol, maxCol, level)` mark rows or columns for collapsible grouping in Excel. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Outline") // Summary row (level 0) s.AddRow().AddCell().SetString("Total") // Detail rows (level 1 — collapsible under Total) for _, item := range []string{"Item A", "Item B", "Item C"} { r := s.AddRow() r.SetOutlineLevel(1) r.AddCell().SetString(item) } // Group columns 2-3 at outline level 1 s.SetOutlineLevel(2, 3, 1) if err := f.Save("outline.xlsx"); err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Save XLSX to File or Write to an io.Writer Source: https://context7.com/tealeg/xlsx/llms.txt Use `File.Save` to write a workbook to a file path, or `File.Write` to stream it to any `io.Writer`, such as an HTTP response. ```go package main import ( "bytes" "log" "net/http" xlsx "github.com/tealeg/xlsx/v3" ) func handler(w http.ResponseWriter, r *http.Request) { f := xlsx.NewFile() s, _ := f.AddSheet("Data") row := s.AddRow() row.AddCell().SetString("Hello from HTTP!") var buf bytes.Buffer if err := f.Write(&buf); err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") w.Header().Set("Content-Disposition", `attachment; filename="output.xlsx"`) w.Write(buf.Bytes()) } func main() { http.HandleFunc("/download", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Cell Styling Source: https://context7.com/tealeg/xlsx/llms.txt Covers how to apply custom styles to cells, including font properties, fill colors, borders, and alignment using `GetStyle()` or `NewStyle()` and `SetStyle()`. ```APIDOC ## Cell Styling — Style, Font, Fill, Border `cell.GetStyle()` or `xlsx.NewStyle()` returns a `*Style` you can configure with font properties, fill color (solid pattern), borders, and alignment, then apply with `cell.SetStyle(style)`. ### Method Signatures `func (c *Cell) GetStyle() *Style` `func xlsx.NewStyle() *Style` `func (c *Cell) SetStyle(style *Style)` ### Style Object Properties - **Font** (*Font) - Font properties (Size, Name, Bold, Color, etc.). - **Fill** (Fill) - Fill properties (PatternType, FgColor, etc.). - **Border** (Border) - Border properties. - **Alignment** (Alignment) - Alignment properties (Horizontal, Vertical, WrapText, etc.). - **ApplyFont** (bool) - Whether to apply font settings. - **ApplyFill** (bool) - Whether to apply fill settings. - **ApplyBorder** (bool) - Whether to apply border settings. - **ApplyAlignment** (bool) - Whether to apply alignment settings. ### Example Usage ```go style := xlsx.NewStyle() style.Font = xlsx.Font{ Size: 14, Name: "Arial", Bold: true, Color: xlsx.RGB_Dark_Red, // "FF9C0006" } style.Fill = xlsx.Fill{ PatternType: xlsx.Solid_Cell_Fill, FgColor: xlsx.RGB_Light_Red, // "FFFFC7CE" } style.Border = *xlsx.NewBorder("thin", "thin", "thin", "thin") style.Alignment = xlsx.Alignment{ Horizontal: "center", Vertical: "center", WrapText: true, } style.ApplyFont = true style.ApplyFill = true style.ApplyBorder = true style.ApplyAlignment = true cell.SetStyle(style) ``` ``` -------------------------------- ### SetDefaultFont Source: https://context7.com/tealeg/xlsx/llms.txt Explains how to set a global default font for all new styles created within the library using `SetDefaultFont`. ```APIDOC ## SetDefaultFont `xlsx.SetDefaultFont(size, name)` changes the global default font used when creating new `Style` objects. Call it once at startup before creating any files. ### Method Signature `func SetDefaultFont(size int, name string)` ### Parameters - **size** (int) - The default font size. - **name** (string) - The default font name. ### Example Usage ```go // Override library default (12pt Verdana) xlsx.SetDefaultFont(11, "Calibri") ``` ``` -------------------------------- ### Set Row Height in xlsx Source: https://context7.com/tealeg/xlsx/llms.txt Shows how to set row height using PostScript points (pt) or centimetres (cm). The library handles the conversion for SetHeightCM. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Heights") // Tall header row (40pt ≈ 53px) header := s.AddRow() header.SetHeight(40) header.AddCell().SetString("Header") // 1 cm data rows for i := 0; i < 5; i++ { row := s.AddRow() row.SetHeightCM(1.0) row.AddCell().SetInt(i + 1) } if err := f.Save("heights.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Access Cell by Coordinates in xlsx Source: https://context7.com/tealeg/xlsx/llms.txt Explains how to access a specific cell using zero-based row and column integers, equivalent to Excel's A1 notation. The `Cell` method creates the cell if it doesn't exist. ```go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f, err := xlsx.OpenFile("data.xlsx") if err != nil { log.Fatal(err) } sheet := f.Sheets[0] // Read cell B3 (row=2, col=1, zero-based) cell, err := sheet.Cell(2, 1) if err != nil { log.Fatal(err) } val, _ := cell.FormattedValue() fmt.Printf("B3 = %s\n", val) // Get coordinates back col, row := cell.GetCoordinates() fmt.Printf("Coordinates: col=%d row=%d\n", col, row) // col=1 row=2 } ``` -------------------------------- ### Create Drop-Down Lists and Range Constraints with Data Validation Source: https://context7.com/tealeg/xlsx/llms.txt Use `NewDataValidation` to create rules for cell ranges. Attach to cells with `SetDataValidation` or to sheets with `AddDataValidation`. Supports drop-down lists and range constraints like whole numbers between a min/max. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Form") // Drop-down in A1 row := s.AddRow() cell := row.AddCell() cell.SetString("Choose status:") dv := xlsx.NewDataValidation(0, 0, 0, 0, true) // row0, col0, single cell if err := dv.SetDropList([]string{"Pending", "Active", "Closed"}); err != nil { log.Fatal(err) } title := "Status" msg := "Select a status from the list" dv.SetInput(&title, &msg) cell.SetDataValidation(dv) // Whole-number constraint on B1 (1–100) numCell := row.AddCell() numDv := xlsx.NewDataValidation(0, 1, 0, 1, false) numDv.SetRange(1, 100, xlsx.DataValidationTypeWhole, xlsx.DataValidationOperatorBetween) errTitle := "Invalid" errMsg := "Enter a whole number between 1 and 100" numDv.SetError(xlsx.StyleStop, &errTitle, &errMsg) numCell.SetDataValidation(numDv) if err := f.Save("form.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Convert XLSX File to Slice of Strings in Go Source: https://context7.com/tealeg/xlsx/llms.txt Provides convenience functions `xlsx.FileToSlice` and `xlsx.FileToSliceUnmerged` to read an entire workbook into a `[][][]string`. `FileToSliceUnmerged` expands merged cells to their origin value. ```Go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { data, err := xlsx.FileToSlice("matrix.xlsx") if err != nil { log.Fatal(err) } // data[sheetIndex][rowIndex][colIndex] fmt.Println("A1:", data[0][0][0]) // First cell of first sheet // With merged cell expansion expanded, err := xlsx.FileToSliceUnmerged("merged.xlsx") if err != nil { log.Fatal(err) } // Covered cells now hold the value of their origin cell fmt.Println(expanded[0]) } ``` -------------------------------- ### Iterate Over Rows Source: https://github.com/tealeg/xlsx/blob/master/tutorial/tutorial.adoc Iterates through each row in a sheet using a provided visitor function. The visitor function receives a pointer to the row and should return an error if processing fails. ```go func rowVisitor(r *xlsx.Row) error { fmt.Println(r) return nil } func rowStuff() { filename := "samplefile.xlsx" wb, err := xlsx.OpenFile(filename) if err != nil { panic(err) } sh, ok := wb.Sheet["Sample"] if !ok { ``` -------------------------------- ### Add Hyperlinks to Cells Source: https://context7.com/tealeg/xlsx/llms.txt Use `Cell.SetHyperlink` to attach external URLs or internal sheet references to cells. Optional display text and tooltips can be provided. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Links") row := s.AddRow() // External hyperlink ext := row.AddCell() ext.SetHyperlink("https://golang.org", "Go Website", "Visit golang.org") // Internal cross-sheet link internal := row.AddCell() internal.SetHyperlink("#Sheet2!A1", "Go to Sheet2", "") if err := f.Save("links.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Sheet.SetColWidth / Sheet.SetColAutoWidth Source: https://context7.com/tealeg/xlsx/llms.txt Details how to set explicit column widths or automatically adjust column widths based on content using `SetColWidth` and `SetColAutoWidth`. ```APIDOC ## Sheet.SetColWidth / Sheet.SetColAutoWidth `Sheet.SetColWidth(min, max, width)` sets explicit column widths (in character units, 1-based). `Sheet.SetColAutoWidth(colIndex, widthFunc)` scans all row values in the column and sets the width to fit the widest content using the provided scale function. ### Method Signatures `func (s *Sheet) SetColWidth(min, max, width float64)` `func (s *Sheet) SetColAutoWidth(colIndex int, widthFunc AutoWidthFunc)` ### Parameters - **min** (float64) - The starting column index (1-based). - **max** (float64) - The ending column index (1-based). - **width** (float64) - The desired width for the columns. - **colIndex** (int) - The column index (1-based) to auto-adjust. - **widthFunc** (AutoWidthFunc) - A function to scale the calculated width (e.g., `xlsx.DefaultAutoWidth`). ### Example Usage ```go // Set explicit width for column 3 (Score) s.SetColWidth(3, 3, 10) // Auto-fit column 1 (Name) using default scale if err := s.SetColAutoWidth(1, xlsx.DefaultAutoWidth); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Sheet.Col / NewColForRange / Col.SetStyle Source: https://context7.com/tealeg/xlsx/llms.txt `NewColForRange(min, max)` creates a column definition spanning a range (1-based). Apply it to a sheet via `sheet.SetColParameters(col)` to set width, style, outline level, or hidden state for whole columns at once. ```APIDOC ## Sheet.Col / NewColForRange / Col.SetStyle `NewColForRange(min, max)` creates a column definition spanning a range (1-based). Apply it to a sheet via `sheet.SetColParameters(col)` to set width, style, outline level, or hidden state for whole columns at once. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Styled Cols") // Make column 1 wide and bold-header-colored col := xlsx.NewColForRange(1, 1) col.SetWidth(20) headerStyle := xlsx.NewStyle() headerStyle.Fill = xlsx.Fill{ PatternType: xlsx.Solid_Cell_Fill, FgColor: xlsx.RGB_Dark_Green, } headerStyle.Font = xlsx.Font{Color: xlsx.RGB_White, Bold: true, Size: 12} headerStyle.ApplyFill = true headerStyle.ApplyFont = true col.SetStyle(headerStyle) s.SetColParameters(col) // Hide columns 3-5 hidden := xlsx.NewColForRange(3, 5) h := true hidden.Hidden = &h s.SetColParameters(hidden) row := s.AddRow() row.AddCell().SetString("Visible") row.AddCell().SetString("Visible 2") row.AddCell().SetString("Hidden") if err := f.Save("col_style.xlsx"); err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Process Large XLSX Files with Disk Storage Source: https://context7.com/tealeg/xlsx/llms.txt Use `xlsx.UseDiskVCellStore` to handle very large XLSX files by storing cell data on disk. Remember to call `sheet.Close()` to clean up temporary files. ```go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f, err := xlsx.OpenFile("10_million_rows.xlsx", xlsx.UseDiskVCellStore) if err != nil { log.Fatal(err) } sheet := f.Sheets[0] defer sheet.Close() // removes temp files on disk count := 0 err = sheet.ForEachRow(func(row *xlsx.Row) error { count++ return nil }, xlsx.SkipEmptyRows) if err != nil { log.Fatal(err) } fmt.Printf("Total rows: %d\n", count) } ``` -------------------------------- ### Cell.Merge Source: https://context7.com/tealeg/xlsx/llms.txt Demonstrates how to merge cells in an Excel sheet using the `Merge` method. This allows a single cell to span across multiple columns and rows. ```APIDOC ## Cell.Merge — Merging Cells `Cell.Merge(hcells, vcells)` spans a cell across additional columns (HMerge) and/or rows (VMerge). Both values are relative offsets from the origin cell. ### Method Signature `func (c *Cell) Merge(hcells, vcells int)` ### Parameters - **hcells** (int) - The number of additional columns to span. - **vcells** (int) - The number of additional rows to span. ### Example Usage ```go // Merge A1 across 3 columns (A1:C1) and 2 rows (A1:A2) titleRow := s.AddRow() title := titleRow.AddCell() title.SetString("Q1 Sales Report") title.Merge(2, 1) // span 3 cols, 2 rows ``` ``` -------------------------------- ### Accessing Cells by Coordinates Source: https://context7.com/tealeg/xlsx/llms.txt Explains how to access a specific cell using its zero-based row and column coordinates with `Sheet.Cell(row, col)`. It also shows how to retrieve coordinates from a cell. ```APIDOC ## Sheet.Cell — Access Cell by Coordinates `Sheet.Cell(row, col int)` retrieves (and if necessary creates) the cell at zero-based row/column coordinates, corresponding to Excel's `A1 = (0,0)`. ```go package main import ( "fmt" "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f, err := xlsx.OpenFile("data.xlsx") if err != nil { log.Fatal(err) } sheet := f.Sheets[0] // Read cell B3 (row=2, col=1, zero-based) cell, err := sheet.Cell(2, 1) if err != nil { log.Fatal(err) } val, _ := cell.FormattedValue() fmt.Printf("B3 = %s\n", val) // Get coordinates back col, row := cell.GetCoordinates() fmt.Printf("Coordinates: col=%d row=%d\n", col, row) // col=1 row=2 } ``` ``` -------------------------------- ### Freeze Panes to Lock Rows and Columns Source: https://context7.com/tealeg/xlsx/llms.txt Configure a `xlsx.Pane` struct and assign it to `Sheet.SheetViews` to freeze panes. This keeps specified rows and/or columns visible while scrolling. Ensure `XSplit` and `YSplit` correctly define the frozen area. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Frozen") // Header row header := s.AddRow() for _, h := range []string{"ID", "Name", "Value"} { header.AddCell().SetString(h) } // Freeze the first row (row 1) and first column (col A) pane := xlsx.Pane{ XSplit: 1, // freeze columns up to col 1 YSplit: 1, // freeze rows up to row 1 TopLeftCell: "B2", // top-left cell of the scrollable area ActivePane: "topRight", // "topRight", "bottomLeft", or "bottomRight" State: "frozen", } s.SheetViews = []xlsx.SheetView{{Pane: &pane}} if err := f.Save("frozen.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Set Various Cell Data Types Source: https://context7.com/tealeg/xlsx/llms.txt Utilize typed setters like `SetString`, `SetInt`, `SetFloat`, `SetBool`, `SetDateTime`, and `SetDate` on `Cell` objects. `SetValue` can automatically infer the type. ```go package main import ( "fmt" "log" "time" xlsx "github.com/tealeg/xlsx/v3" ) func main() { f := xlsx.NewFile() s, _ := f.AddSheet("Types") row := s.AddRow() row.AddCell().SetString("plain text") row.AddCell().SetInt(42) row.AddCell().SetInt64(9876543210) row.AddCell().SetFloat(3.14159) row.AddCell().SetFloatWithFormat(1234567.89, "#,##0.00") row.AddCell().SetBool(true) row.AddCell().SetDateTime(time.Now()) row.AddCell().SetDate(time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC)) row.AddCell().SetFormula("SUM(B1:B10)") // SetValue dispatches by type row2 := s.AddRow() row2.AddCell().SetValue("auto") row2.AddCell().SetValue(100) row2.AddCell().SetValue(time.Now()) row2.AddCell().SetValue(nil) // becomes empty string // Read back formatted value cell, err := s.Cell(0, 4) // row 0, col 4 → "#,##0.00" formatted cell if err != nil { log.Fatal(err) } v, _ := cell.FormattedValue() fmt.Println("Formatted:", v) // "1,234,567.89" } ``` -------------------------------- ### Cell.SetRichText Source: https://context7.com/tealeg/xlsx/llms.txt Explains how to apply rich text formatting to a cell, enabling the use of multiple styles (font, size, color, bold, italic) within a single cell. ```APIDOC ## Cell.SetRichText — Rich Text in Cells `SetRichText` stores multiple styled text runs in a single cell, allowing mixed fonts, colors, sizes, bold/italic, and underline within one cell. ### Method Signature `func (c *Cell) SetRichText(runs []RichTextRun)` ### Parameters - **runs** ([]xlsx.RichTextRun) - A slice of `RichTextRun` structs, each defining a text segment and its associated font style. ### Example Usage ```go cell.SetRichText([]xlsx.RichTextRun{ { Font: &xlsx.RichTextFont{ Bold: true, Size: 14, Name: "Arial", Color: xlsx.NewRichTextColorFromARGB(255, 255, 0, 0), // red }, Text: "Alert: ", }, { Font: &xlsx.RichTextFont{ Italic: true, Size: 12, }, Text: "action required", }, }) ``` ``` -------------------------------- ### Set Default Font Source: https://context7.com/tealeg/xlsx/llms.txt Use xlsx.SetDefaultFont(size, name) to change the global default font for new Style objects. Call this once at startup before creating any files. ```go package main import ( "log" xlsx "github.com/tealeg/xlsx/v3" ) func main() { // Override library default (12pt Verdana) xlsx.SetDefaultFont(11, "Calibri") f := xlsx.NewFile() s, _ := f.AddSheet("Sheet1") row := s.AddRow() row.AddCell().SetString("This cell uses 11pt Calibri by default") if err := f.Save("calibri.xlsx"); err != nil { log.Fatal(err) } } ```