英文:
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"?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论