How to read a XLSX file with multiple Sheets in Golang?

In the last post, we saw how to use Golang to read and write csv files. In this tutorial, we will look at how to read an xlsx file using Golang.

Read xlsx file

 

Xlsx is a commonly used extension in business, and most people use it to transfer data from one place to another, such as Google Sheets, which accepts xlsx format, and Windows, which provides many features and properties in its excel sheet.

In terms of security, xlsx is also an excellent format for exporting and importing data. However, the real problem here is for you as a golang developer to read that xlsx file using golnag.

For reading a xlsx file there are multiple third party library, but we are going to use below library:

 "github.com/360EntSecGroup-Skylar/excelize"

This excelize documentation is good and also give us multiple example to perform operation on excel file. 

How to read a XLSX file with multiple Sheets in Go or Golang?

In this program we are going to read multiple sheet of a xlsx file and their data using golang.

 

package main

import (
	"fmt"
	"log"

	"github.com/360EntSecGroup-Skylar/excelize"
)

//ReadXlsxFile read given xlsx file using golang
func ReadXlsxFile(fileName string) {
	xlsx, err := excelize.OpenFile(fileName)
	if err != nil {
		log.Fatalf("File Not exists: %s", err.Error())
		return
	}
	// Get value from cell by given worksheet name and axis.
	for _, name := range xlsx.GetSheetMap() {
		rows, err := xlsx.GetRows(name)
		if err != nil {
			log.Fatalf("RowsRead rows:%s", err.Error())
			return
		}
		for _, row := range rows {
			for _, colCell := range row {
				fmt.Print(colCell, "\t")
			}
			fmt.Println()
		}
	}

	fmt.Printf("Read Successfully:%s\n", fileName)
}

func main() {
	// give your file path
	ReadXlsxFile("testing.xlsx")
}

 

 

Above is the simple program to read xlsx file, based on your requirement you can write your wrapper function on this to get use of data.

In other post i alread posted to how to read csv file using golang.

Let me know in comment if you have get any issue while running this code.

Post a Comment

0 Comments