How to read excel file by row in Go language?

1.4k views Asked by At

In my project, I using qax-os/excelize library version v2.7.1 for read excel file in Go language. But when I run my app on machine with 32Mi ram I got error out of memory.

This is sample of my code:

func main() {
    f, err := excelize.OpenFile("electricinfo.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer func() {
        // Close the spreadsheet.
        if err := f.Close(); err != nil {
            fmt.Println(err)
        }
    }()

    // Get all the rows in the sheet mydistrict.
    rows, err := f.GetRows("mydistrict")
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, row := range rows {
        for _, colCell := range row {
            // ...Business logic
        }
        fmt.Println()
    }
}

How I can read excel row one by one, something like

func main() {
    rowNumber := 1
    for {
        // Loop through each row in the csv
        record, err := csvReader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            // ... Block of code
            continue
        }
    }
}
1

There are 1 answers

0
Raihan Khan On

You can try using xlsxreader package, A low-memory high performance library for reading data from an xlsx file for streaming data instead of loading into RAM. Alternative, You can use xlsx-tables.