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

使用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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条