In my code below I'm using the exclize library to read data from an excel sheet.
My problem is that the .GetRows
method reads the entier sheet when I'm only interested in getting the data from a few columns.
Looking through the goDoc I couldn't find a method that gives you the data based on column index or name.
Is there a way, in spite of this, to only read the data from a select few columns? Or limit the range of the .GetRows
method somehow
Here's the code:
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
type AllData struct {
Name, Team, SSN string
}
var mapping []AllData
func main() {
fileName := "Blad1"
xlsx, err := excelize.OpenFile(fileName + ".xlsx")
if err != nil {
fmt.Println(err)
return
}
rows := xlsx.GetRows(fileName)
for _, row := range rows[1:] {
mapping = append(mapping, AllData{ Name: row[0] })
}
m := map[string]interface{}{
"Data": mapping,
}
fmt.Println(m["Data"])
}
It looks like there are at least a couple more ways
by using rows iterator
rows, err := xlsx.Rows("Sheet1")
if err != nil {
log.Fatal(err)
}
for rows.Next() {
row := rows.Columns()
fmt.Printf("%s\t%s
", row[1], row[3]) // Print values in columns B and D
}
or if you know the exact range
n := 10001
for i := 1; i < n; i++ {
b := xlsx.GetCellValue("Sheet1", fmt.Sprintf("B%d", i))
d := xlsx.GetCellValue("Sheet1", fmt.Sprintf("D%d", i))
fmt.Printf("%s\t%s
", b, d) // Print values in columns B and D
}
I didn't go through the source of the library so it may or may not make a difference in terms of performance and (or) memory usage.