Search code examples
arraysexcelgoexcelize

How to get the values of a particular column in excel sheet and make as an array and pass that array as input values in golang?


I have a column in excel sheet with random numbers generated from 1 to 1 million.

I would like to read this particular column and store in an array in golang.

Later, i would like to pass this array as my request to my load balancer which will read the values in my column and do the load balancing accordingly.

I am using "github.com/360EntSecGroupSkylar/excelize" for creating an excel file

Thank you


Solution

  • Now I assume that all the other things such as creating, reading, etc. are out of the scope of this question and you have a struct file that has the current excel file.
    In this case, you can try following:

    func GetCol(f *excelize.File, sheet string, col rune) ([]string, error) {
        colIndex := int(col) - 'A'
        cols, err := f.GetCols(sheet)
        if err != nil {
            return nil, err
        }
        if colIndex >= len(cols) {
            return nil, errors.New("column index out of bound")
        }
        return cols[colIndex], nil
    }
    

    And use this as following:

    cols, _ := GetCol(f, "Sheet1", 'B')
    
    for _, col := range cols {
        fmt.Println(col)
    }
    

    Make sure to use capital column index. You can modify the function to take index directly. Also, make sure to handle errors your way.