想要達到我正在用 Go 構建一個應用程序。它是從 excel 文件創建一個 ruby 文件。如果xx中有值,我想把它放在數據中,如果它是空白的,我想跳過這個過程。但是,如果我如下所示輸入 nil,則會出現錯誤。xx = xx + 19if row[xx] ! = nil { data["IndustryId"] = row[xx]; }invalid operation: row[xx] != nil (mismatched types string and nil)我希望你能幫助我。代碼測試.gofunc main() { excel_file, err := excelize.OpenFile("./excel/data.xlsx") if err != nil { fmt.Println(err) return } seeds := make([]string, 0, 1000) seeds = append(seeds, "# Seed") seeds = append(seeds, "# " + time.Now().Format("RFC3339")) seeds = append(seeds, "") tpl := template.Must(template.ParseFiles(`test.tmpl`)) rows, err := excel_file.GetRows("Test") for i, row := range rows { if i != 0 { xx := 2 data := map[string]string{ "Id": row[xx], } xx = xx + 19 if row[xx] != nil { data["IndustryId"] = row[xx]; } if err := tpl.Execute(&output, data); err != nil { fmt.Println(err) return } seeds = append(seeds, output.String()) } } export_file("./seeds/import_test.rb", seeds)}
2 回答

明月笑刀無情
TA貢獻1828條經驗 獲得超4個贊
rows, err := excel_file.GetRows("Test")
這rows
是類型[][]string
?,F在當你這樣做時:
for i, row := range rows { ... }
row
是的[]string
,現在如果你索引它,你會得到一個字符串。
字符串的零值是""
(空字符串) 而不是nil
。因此,請將其與""
而不是進行比較nil
。這里:
row[xx] != ""

波斯汪
TA貢獻1811條經驗 獲得超4個贊
您應該 Trim row[xx] 以確保該行不只包含空格并將其與“”而不是 nil 進行比較。
import strings
....
strings.TrimSpace(row[xx]) != ""
- 2 回答
- 0 關注
- 116 瀏覽
添加回答
舉報
0/150
提交
取消