dongxu1875 2018-07-17 16:16
浏览 70
已采纳

如何读取数组或切片的子集

In Go, I can now read an excel file and put it into a slice.

I know also how to read the value of a specific cell.

But I would like now to read a subset of the initial slice, so basically read only rows 10 to 15 and columns 23 to 25 for example.

My code below does not do that, it reads rows 35 and 36 and all columns. How can I read only columns 23 to 25 into df2?

package main

import (
    "fmt"

    "github.com/360EntSecGroup-Skylar/excelize"
)

func main() {
    xlsx, err := excelize.OpenFile("/media/Snaps/test.xlsm")
    if err != nil {
        fmt.Println(err)
        return
    }

    rows := xlsx.GetRows("ticker")

    df2 := rows[10:15][23:25]
    fmt.Println(df2)
}
  • 写回答

1条回答 默认 最新

  • dty3416 2018-07-17 17:26
    关注

    The key here I think is to stop thinking of it as rows and colums; in your code, you're operating on slices of slices. You can slice the outer level to get the rows you want, then iterate those to get the columns you want from each row. If you just take slices, though, all of the data you're not using will still be held in memory as part of the arrays backing the slices. For memory efficiency, you'll probably want to copy the desired data to completely new slices with new backing arrays:

        rows := xlsx.GetRows("ticker")
    
        df2 := make([][]string, 5) // I don't know what data type the cells are, assuming string, adjust the number to the number of rows you want to avoid unnecessary allocations)
        idx := 0
        for _, row := range rows[10:15] { // iterate over desired rows
            df2row := make([]string, 2) // again, assuming 2 columns of string cells, adjust as needed
            copy(df2row, row[23:25]) // copy desired columns to new row slice
            df2[idx] = df2row
            idx++
        }
    
        fmt.Println(df2)
    

    There's an excellent, detailed rundown of slice operations here: https://blog.golang.org/go-slices-usage-and-internals

    Here's a runable playground example with generated dummy data: https://play.golang.org/p/wRKcTpnTUA2

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?