This was developed as an extension for the
xlsx
package. It contains the following utilities to manipulate
excel files:
Sort()
, SortByHeaders
: multi-column (reverse) sort of selected rows (Note that columns are one based, not zero based to make reverse sort possible.)AddBool()
, AddInt()
, AddFloat()
, ...: shortcut to add a cell to a row with the right type.NewStyle()
: create a style and set the ApplyFill
, ApplyFont
, ApplyBorder
and ApplyAlignment
automatically.NewStyles()
: create a slice of styles based on a color paletteSheets
: access sheets by name instead of by indexCol
: access cell values of a row by column header titleSetRowStyle
: set style of all cells in a rowToString
: convert a xlsx.Row to a slice of strings
Example
Add cells and retrieve cell values by column title header:
type Item struct {
Name string
Price float64
Amount int
}
sheet, err := xlsx.NewFile().AddSheet("Shopping Basket")
if err != nil {
fmt.Println(err)
return
}
var titles = []string{"item", "price", "amount", "total"}
header := sheet.AddRow()
for _, title := range titles {
xlsxtra.AddString(header, title)
}
style := xlsxtra.NewStyle(
"00ff0000",
&xlsx.Font{Size: 10, Name: "Arial", Bold: true},
nil,
nil,
)
xlsxtra.SetRowStyle(header, style)
var items = []Item{
{"chocolate", 4.99, 2},
{"cookies", 6.45, 3},
}
var row *xlsx.Row
for i, item := range items {
row = sheet.AddRow()
xlsxtra.AddString(row, item.Name)
xlsxtra.AddFloat(row, item.Price, "0.00")
xlsxtra.AddInt(row, item.Amount)
xlsxtra.AddFormula(row,
fmt.Sprintf("B%d*C%d", i+1, i+1), "0.00")
}
col := xlsxtra.NewCol(header)
price, err := col.Float(row, "price")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(price)
Multi column sort:
sheet, err := xlsxtra.OpenSheet(
"xlsxtra_test.xlsx", "sort_test.go")
if err != nil {
fmt.Println(err)
return
}
xlsxtra.Sort(sheet, 1, -1,
3,
-2,
6,
)
for _, row := range sheet.Rows {
fmt.Println(strings.Join(xlsxtra.ToString(row), ", "))
}
fmt.Println()
headers := xlsxtra.NewHeaders(sheet.Rows[0])
err = xlsxtra.SortByHeaders(sheet, 1, -1, headers,
"-amount",
"first_name",
)
if err != nil {
fmt.Println(err)
return
}
for _, row := range sheet.Rows {
fmt.Println(strings.Join(xlsxtra.ToString(row), ", "))
}
Documentation
See godoc for more documentation and examples.
License
Released under the MIT License.