doudeng2184
2018-10-24 13:34
浏览 392
已采纳

使用go遍历特定的excel列

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"])
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyou8087 2018-10-24 19:04
    已采纳

    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.

    点赞 评论

相关推荐 更多相似问题