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 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型