在Golang中读取Excel文件时出现错误。

huangapple go评论100阅读模式
英文:

Error reading an excel file in golang

问题

我尝试了下面的代码,但是出现了错误

> "multiple-value cell.String() in single-value context"

代码

 package main
import (
"fmt"
"github.com/tealeg/xlsx"
 )
 func main() { 
     excelFileName := "test.xlsx"
     xlFile, err := xlsx.OpenFile(excelFileName)
     if err != nil {

     }
 for _, sheet := range xlFile.Sheets {
    for _, row := range sheet.Rows {
          for _, cell := range row.Cells {
            fmt.Printf("%s ", cell.String(), "123")
  }
            fmt.Printf("\n")
  }
  }
 }
}
英文:

I was trying the below code but I get an error

> "multiple-value cell.String() in single-value context"

Code

 package main
import (
"fmt"
"github.com/tealeg/xlsx"
 )
 func main() { 
     excelFileName := "test.xlsx"
     xlFile, err := xlsx.OpenFile(excelFileName)
     if err != nil {

     }
 for _, sheet := range xlFile.Sheets {
    for _, row := range sheet.Rows {
          for _, cell := range row.Cells {
            fmt.Printf("%s ", cell.String(), "123")
  }
            fmt.Printf("\n")
  }
  }
 }
}

答案1

得分: 3

将以下代码进行翻译:

for _, cell := range row.Cells {
    fmt.Printf("%s ", cell.String(), "123")
}

翻译为:

for _, cell := range row.Cells {
    val, _ := cell.String()
    fmt.Printf("%s ", val)
}
英文:

change

for _, cell := range row.Cells {
    fmt.Printf("%s ", cell.String(), "123")
}

to

for _, cell := range row.Cells {
    val, _ := cell.String()
    fmt.Printf("%s ", val)
}

答案2

得分: 0

你正在尝试将返回多个值的函数作为单个参数传递给fmt.Printf()

如果你认为不会出现任何错误,你可以将其赋值给_并忽略它,但你真的应该准备好处理错误。这就是为什么Go语言强制使用变量,并且不会自动丢弃其他返回值(比如cell.String()的错误)。

val, err := cell.String()
if err != nil {
    // 处理错误
}
fmt.Printf("%s ", val) // 你多传了一个参数"123"?
英文:

You are trying to use a function that returns multiple values as a single argument (to fmt.Printf())

If you don't think you will get any errors, you can just assign it to _ and ignore it, but you really should be prepared to handle the error. This is why Go forces you to use variables and why it doesn't automatically discard other return values (like the error from cell.String())

val, err := cell.String()
if err != nil {
    // handle the error
}
fmt.Printf("%s ", val) // you had an extra arg of "123"?

huangapple
  • 本文由 发表于 2016年4月15日 19:37:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/36646114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定