2016-04-27 39 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