Tables and Named Ranges
Add a Worksheet Table
AddTable registers a real worksheet table and writes it as a proper OOXML table part:
sheet := wb.Sheet("Sales")
if err := sheet.AddTable(werkbook.Table{
DisplayName: "SalesTable",
Ref: "A1:D10",
Style: &werkbook.TableStyle{
Name: "TableStyleMedium2",
ShowRowStripes: true,
},
}); err != nil {
log.Fatal(err)
}
Useful Table fields:
Ref- required A1 range such as"A1:D10"DisplayName- the name used in structured referencesColumns- optional explicit column namesHeaderRowCount- defaults to1when left as0TotalsRowCount- number of totals rows at the bottomAutoFilter- enables an auto-filter row
If you omit Name and DisplayName, werkbook generates table names automatically.
Use Structured References in Formulas
Once a table exists, formulas can use Excel-style structured references:
sheet.SetFormula("F1", "SUM(SalesTable[Total])")
sheet.SetFormula("F2", "SalesTable[[#This Row],[Qty]]*SalesTable[[#This Row],[Price]]")
Structured references also work when you open an existing workbook that already contains tables.
Inspect Existing Tables
for _, table := range wb.Tables() {
fmt.Println(table.DisplayName, table.Ref)
}
for _, table := range sheet.Tables() {
fmt.Println(table.DisplayName)
}
Both accessors return copies of the table metadata.
Define Workbook or Sheet-Scoped Names
Named ranges and named formulas are represented by DefinedName:
err := wb.SetDefinedName(werkbook.DefinedName{
Name: "TaxRate",
Value: "Config!$B$2",
LocalSheetID: -1, // workbook scope
})
if err != nil {
log.Fatal(err)
}
For a sheet-scoped name, use the 0-based sheet index:
err = wb.SetDefinedName(werkbook.DefinedName{
Name: "LocalRate",
Value: "Summary!$B$2",
LocalSheetID: wb.SheetIndex("Summary"),
})
Read and Resolve Names
for _, dn := range wb.DefinedNames() {
fmt.Println(dn.Name, dn.Value, dn.LocalSheetID)
}
vals, err := wb.ResolveDefinedName("TaxRate", -1)
if err != nil {
log.Fatal(err)
}
fmt.Println(vals[0][0].Raw())
ResolveDefinedName always returns a 2D slice. A single-cell name comes back as a 1 x 1 grid.
If sheetIndex >= 0, a sheet-scoped name on that sheet takes precedence over a workbook-scoped name with the same text.
Add, Replace, and Delete
Use the right mutator for the behavior you want:
AddDefinedNameappends a new name and does not replace an existing oneSetDefinedNameinserts or replaces by name and scopeDeleteDefinedNameremoves the matching name and scope
if err := wb.DeleteDefinedName("TaxRate", -1); err != nil {
log.Fatal(err)
}