在 linux 系统上从 golang 中的 xls 文件中读取值

Reading values from xls file in golang on linux system

我正在编写一个程序来读取 Go 中的 xls 文件。我正在使用 github.com/extrame/xls 包。 如果它不为空,我想读取每个单元格。 (请注意,有些行在所有 11 列中都有值,但有些行没有。)

我的代码是:

if xlFile, err := Open("Table.xls", "utf-8"); err == nil {
    if sheet1 := xlFile.GetSheet(0); sheet1 != nil {
        fmt.Print("Total Lines ", sheet1.MaxRow, sheet1.Name)
        col1 := sheet1.Rows[0].Cols[0]
        col2 := sheet1.Rows[0].Cols[0]
        for i := 0; i <= (int(sheet1.MaxRow)); i++ {
            row1 := sheet1.Rows[uint16(i)]
            col1 = row1.Cols[0]
            col2 = row1.Cols[11]
            fmt.Print("\n", col1.String(xlFile), ",", col2.String(xlFile))
        }
    }
}

它给出了以下错误:

panic: runtime error: invalid memory address or nil pointer dereference

因为单元格 11 的某些行是空的。

请指教更好的方法或解决方法

我假设如果尾随列为空,则 Cols 切片仅与填写的列数一样大。

在这种情况下,只需执行:

if len(row1.Cols) < 12 {
 // Whatever you want to do with < 12 columns 
} else {
 // Use Cols[11] (12th column) here
}

如果你只想要第一列和最后一列,你可以这样做: rows1.Cols[0]rows1.Cols[len(row1.Cols)-1] 可以处理任意宽的行。

如果可能有空白行,请先检查 len(rows1.Cols) == 0 以确保您不会尝试访问不存在的数据。

在获得 Cols[11] 之前,您是否尝试检查 Cols 长度?

if len(row1.Cols) > 10 {
  col2 = row1.Cols[11]
}else{
  col2 = Col{}
}

检查你提到的 repo 有一个 row.go 文件,其中定义了 Row 结构如下:

type Row struct {
    info *RowInfo
    Cols map[uint16]contentHandler
}

这包含 Cols 键是 uint16 值的映射。因为在 go 中你可以通过以下方式验证映射键是否存在:

if col2, ok := row1.Cols[11]; ok { }

这意味着您可以通过检查单元格是否包含键来测试单元格是否为空。

if col2, ok := row1.Cols[11]; ok { 
    fmt.Print("\n", col2.String(xlFile))
}