How to Read Write an Excel File with Golang
Golang Excelize
In golang, Excelize is a library used to read and write Excel files. This package comes with the API for better working with the sheets and it supports various file formats like xlsx, xlsm, etc.
First install the packages from github using this command in your command prompt or vscode
go get github.com/xuri/excelize@latest
Using @latest at the end is to get the latest version for ease.
Reading the data from an excel file
let's get started with the data reading of an excel file using golang library excelize
We are taking a test file from the library itself and will print some names from the name column with the following code:
package main
import (
"fmt"
"log"
"github.com/xuri/excelize@latest"
)
func main() {
file, error := excelize.OpenFile("test-file.xlsx")
if erro != nil {
log.Fatal(error)
}
name1, error := file.GetCellValue("file1", "B2")
if err != nil {
log.Fatal(error)
}
fmt.Println(name1)
name2, error := file.GetCellValue("file1", "B3")
if error != nil {
log.Fatal(error)
}
fmt.Println(name2)
}
the method used here, i.e. GetCellValue used here is to get the value from a specified cell meaning providing the coordinates of that value along with the sheet name as the parameter. And the error variable is used for error handling, it'll throw us an error if any step fails above. Now, you can understand that we are retrieving the values from column B row 2 and column B row 3.
Write in an excel file
We can create an excel file and can write columns in it as per the following code:
package main
import (
"log"
"github.com/xuri/excelize@latest"
)
func main() {
file := excelize.NewFile() //creates new excel file with one sheet
file.SetCellValue("Sheet1", "A1", "Name")
file.SetCellValue("Sheet1", "A2", "Techsolvo")
file.SetCellValue("Sheet1", "A3", "codersdaily")
if err := file.SaveAs("companies.xlsx"); err != nil { //checking for errors in creating the file
log.Fatal(err)
}
}
This will create a new excel file with sheet1 and it would have a column named "companies" in which starting two are "Techsolvo" & "codersdaily". The SetCellValue method requires three parameters namely:
- name of the sheet
- coordinated to write and
- Values
Now if you want to write/create an existing file, then we could do it with the following code example:
package main
import (
"fmt"
"log"
"github.com/xuri/excelize@latest"
)
func main() {
file := excelize.NewFile() //creating a new sheet
Name := file.NewSheet("new_sheet") //creating the new sheet names
fmt.Println(Name)
file.SetCellValue("new_sheet", "A1", "companies")
file.SetCellValue("new_sheet", "A2", "techsolvo")
file.SetCellValue("new_sheet", "A3", "codersdaily")
file.SetActiveSheet(idx)
if err := file.SaveAs("companies.xlsx"); err != nil { //saving the new sheet in the file names companies
log.Fatal(err)
}
}
This will create a new_sheet named sheet in the file name companies.