首页 > 解决方案 > 从 xls 文件中读取值但未正确读取数值

问题描述

xls 文件中的数值读取不正确,但字符串值正常

file, _ := xls.Open("test.xls", "utf-8")

    sheet := file.GetSheet(0)
    for r := 0; r <= (int(sheet.MaxRow)); r++ {
      row := sheet.Row(r)
      log.Println("column with numeric value: ", row.Col(0))
      log.Println("column with string value: ", row.Col(1))
    }

测试.xls:

123 | test

456 | testing

输出:

column with numeric value: @

column with string value: test

column with numeric value: @

column with string value: testing

如何正确获取数值?

标签: excelgoxls

解决方案


在我的 Ubuntu 18.04 上,我可以打开文件并打印第二列的内容

package main

import (
    "fmt"
    "github.com/extrame/xls"
    "log"
)


func main() {
if xlFile, err := xls.Open("test.xls", "utf-8"); err == nil {
    for i := 0; i < xlFile.NumSheets(); i++ {
        sheet := xlFile.GetSheet(i)
        fmt.Println(sheet.Name)
        for r := 0; r <= (int(sheet.MaxRow)); r++ {
                row := sheet.Row(r)
                log.Println("column ", row.Col(1))
        }
    }
}

}

请特别注意 Col(1) 索引。

输出

Sheet1
2019/04/03 14:28:29 column  test
2019/04/03 14:28:29 column  testi
2019/04/03 14:28:29 column  testing

但是对于数字列,我得到了这个

Sheet1
2019/04/03 14:27:46 column  General
2019/04/03 14:27:46 column  General
2019/04/03 14:27:46 column  General

我保存了与 xlsx 相同的文件。这适用于tealeg/xlsx 包

import (
    "fmt"
    "github.com/tealeg/xlsx"
)

func main() {
    excelFileName := "test.xlsx"
    xlFile, err := xlsx.OpenFile(excelFileName)
    if err != nil {
        err = fmt.Errorf("can not open file!!!", err)
    return
    }
    for _, sheet := range xlFile.Sheets {
        for _, row := range sheet.Rows {
            for _, cell := range row.Cells {
                text := cell.String()
                fmt.Println(text)
            }
        }
    }
}

输出

123
test
788
456
testi
999
789
testing
100

推荐阅读