Creating Workbooks
New Workbook
Create a workbook with the default sheet name (“Sheet1”) or provide a custom name:
wb := werkbook.New()
wb := werkbook.New(werkbook.FirstSheet("Report"))
Setting Cell Values
Use SetValue with A1 notation. werkbook accepts Go native types and converts them automatically:
sheet := wb.Sheet("Report")
sheet.SetValue("A1", "Name") // string
sheet.SetValue("B1", 42) // int → float64
sheet.SetValue("C1", 3.14) // float64
sheet.SetValue("D1", true) // bool
sheet.SetValue("E1", time.Now()) // time.Time → Excel serial number
sheet.SetValue("F1", nil) // clears the cell
Supported types: string, bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, time.Time, and nil.
Adding Formulas
Set formulas without the leading =:
sheet.SetFormula("A5", "SUM(A2:A4)")
sheet.SetFormula("B5", "AVERAGE(B2:B4)")
sheet.SetFormula("C1", "IF(A1>100,\"High\",\"Low\")")
Formulas are evaluated lazily when you call GetValue, or you can force evaluation of all formulas:
wb.Recalculate()
Working with Multiple Sheets
wb := werkbook.New(werkbook.FirstSheet("Summary"))
// Add more sheets
dataSheet, _ := wb.NewSheet("Data")
chartsSheet, _ := wb.NewSheet("Charts")
// Reference across sheets
summary := wb.Sheet("Summary")
summary.SetFormula("A1", "SUM(Data!B2:Data!B100)")
summary.SetFormula("A2", "AVERAGE(Data!C2:Data!C100)")
// List all sheets
for _, name := range wb.SheetNames() {
fmt.Println(name)
}
// Remove a sheet
wb.DeleteSheet("Charts")
Column Width and Row Height
sheet.SetColumnWidth("A", 20.0)
sheet.SetColumnWidth("B", 15.5)
sheet.SetRowHeight(1, 30.0) // header row
Saving
Write the workbook to disk:
err := wb.SaveAs("report.xlsx")
if err != nil {
log.Fatal(err)
}
Full Example
package main
import (
"fmt"
"log"
"time"
"github.com/jpoz/werkbook"
)
func main() {
wb := werkbook.New(werkbook.FirstSheet("Inventory"))
sheet := wb.Sheet("Inventory")
// Headers
headers := []string{"Item", "Quantity", "Unit Price", "Total", "Updated"}
for i, h := range headers {
col := werkbook.ColumnNumberToName(i + 1)
sheet.SetValue(col+"1", h)
}
// Data rows
type item struct {
name string
qty int
price float64
}
items := []item{
{"Laptop", 10, 999.99},
{"Monitor", 25, 349.50},
{"Keyboard", 100, 49.99},
}
for i, it := range items {
row := i + 2
r := fmt.Sprint(row)
sheet.SetValue("A"+r, it.name)
sheet.SetValue("B"+r, it.qty)
sheet.SetValue("C"+r, it.price)
sheet.SetFormula("D"+r, fmt.Sprintf("B%d*C%d", row, row))
sheet.SetValue("E"+r, time.Now())
}
// Summary
sheet.SetValue("A6", "Grand Total")
sheet.SetFormula("D6", "SUM(D2:D4)")
// Column widths
sheet.SetColumnWidth("A", 15)
sheet.SetColumnWidth("D", 12)
sheet.SetColumnWidth("E", 18)
if err := wb.SaveAs("inventory.xlsx"); err != nil {
log.Fatal(err)
}
}