Creating Excel files with Golang
Recently I had come across a use case where I had to generate an Excel file from some data in Golang. It was a simple enough task and I would like to share with you how it was done.
A quick google search for packages in Golang that deal with excel files will give you two results that are most relevant. One was excelize by 360EntSecGroup-Skylar and the other was xlsx by tealeg.
I had a quick glance through both the repos but decided to go with excelize just because my requirements were simple and its readme had pretty much everything I needed.
To demonstrate how to use the package, let us assume we have to generate an excel file listing out the inventory of various shops :).
Installation
go get github.com/360EntSecGroup-Skylar/excelize/v2
This will fetch the golang package.
Creating the file
type Inventory struct {
Name string
Date string
Cake int
Chocolate int
Chips int
}
This is the struct we will be working with, Simple enough :). First we need to initialize an excelize file struct, which can be done with the following line
f := excelize.NewFile()
This will create a sheet called Sheet1 by default. Now to set the column headings
f.SetCellValue("Sheet1", "A1", "Shop Name")
f.SetCellValue("Sheet1", "B1", "Date")
f.SetCellValue("Sheet1", "C1", "Cake")
f.SetCellValue("Sheet1", "D1", "Chocolate")
f.SetCellValue("Sheet1", "E1", "Chips")
Since we already know the columns, it is pretty straightforward to set the column headings. The above lines will set “Shop Name” in cell A1,”Date” in B1 and so on.
func SaveToExcel(inventory []Inventory) error {
f := excelize.NewFile() f.SetCellValue("Sheet1", "A1", "Shop Name")
f.SetCellValue("Sheet1", "B1", "Date")
f.SetCellValue("Sheet1", "C1", "Cake")
f.SetCellValue("Sheet1", "D1", "Chocolate")
f.SetCellValue("Sheet1", "E1", "Chips")for i := 0; i < len(inventory); i++ {
f.SetCellValue("Sheet1", "A"+strconv.Itoa(i+2), inventory[i].Name)
f.SetCellValue("Sheet1", "B"+strconv.Itoa(i+2), inventory[i].Date)
f.SetCellValue("Sheet1", "C"+strconv.Itoa(i+2), inventory[i].Cake)
f.SetCellValue("Sheet1", "D"+strconv.Itoa(i+2), inventory[i].Chocolate)
f.SetCellValue("Sheet1", "E"+strconv.Itoa(i+2), inventory[i].Chips)}if err := f.SaveAs("inventory.xlsx"); err != nil {
return err
}return nil
}
Putting it all together, here we have a small function that initializes the excel sheet, sets the headings and then iterates over the slice and sets the value for each cell. At the end the data is saved into an excel file named “inventory.xlsx”.
For a complete working example, check out this repo here.
Conclusion
That’s pretty much it. The package was very easy to get started with and has much more to offer. You can take a look at the repo and documentation to get a better idea.