2016-04-27 98 views
0

我正在编写一个程序来读取Go中的xls文件。我正在使用github.com/extrame/xls包。 我想读取每个单元格,如果它不是空的。 (注意:某些行将具有值在所有11列,但有些则不会。)在Linux系统中读取golang中xls文件的值

我的代码是:由于电池11

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

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)) 
     } 
    } 
} 

它提供了以下错误空的一些行。

请提供更好的方法或解决方案。

回答

1

检查您提到的回购有row.go文件。在这个文件中被定义的结构如下:

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

这包含Cols地图哪些键uint16值。因为在旅途中,你可以验证,如果地图键以下列方式存在:

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

这意味着你可以测试,如果细胞不通过检查他们是否包含密钥空。

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

,帮助 谢谢你simo endre – Hardy

+0

伟大的,它帮助。 –

0

我假设如果您有空尾列,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以确保您不试图访问不存在的数据。

+0

如果中间还有空单元格,这个工作就可以吗?说cell 2 cell 4也可以是空的。 所以我想知道,如果该特定单元格为空 – Hardy

+0

更新的答案为可变宽度的行 –

0

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

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

这将工作,如果在中间也有空单元格吗? – Hardy

+0

是的。如果只有Cols有12个或更多元素,它可以访问'Cols [11]'。 – rootatdarkstar