Home > database >  Loop throw column cells in golang and excelize
Loop throw column cells in golang and excelize

Time:06-19

I was wondered how to loop over column cells of excel sheet in golang, here is my excel file:

enter image description here

I have tried this piece of code for other reason

package main

import (
    "fmt"
    "github.com/xuri/excelize/v2"
)

func main() {

    f, err := excelize.OpenFile("pricematching.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }

    // Get all the rows in the sheet1 section.
    rows, err := f.GetCellValue("sheet1", "A2")

    fmt.Print(rows, "\t")

}


CodePudding user response:

No matter how's your excel file, this is the way to read each cell:

xlsxFile, error := excelize.OpenFile(filePath)
for _, sheetName := range xlsxFile.GetSheetMap() {
   for rowIndex, rowValues := range xlsxFile.GetRows(sheetName) {
      for columnIndex, columnValue := range rowValues {
         // do what ever you want here
      }
   }
}

CodePudding user response:

Not sure what exactly you need, but this is a simple way to get all cells in a column (if you know how many rows you want to read):

package main

import (
    "fmt"
    "github.com/xuri/excelize/v2"
)

func main() {
    f, err := excelize.OpenFile("pricematching.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }

    columnName := "A"
    sheetName := "sheet1"
    totalNumberOfRows := 20

    for i := 1; i < totalNumberOfRows; i   {
        cellName := fmt.Sprintf("%s%d", columnName, i)
        // fmt.Println(cellName)
        cellValue, err := f.GetCellValue(sheetName, cellName)
        fmt.Printf("%s\t", cellValue)
    }
}
  • Related