版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1334272
https://github.com/tealeg/xlsx/issues/200
They like the same excel,but the different results.
my code:
package main
import (
"fmt"
"strconv"
"github.com/tealeg/xlsx"
)
package main
import (
"fmt"
"strconv"
"github.com/tealeg/xlsx"
)
type Catalog struct {
Id int64
Name string
ParentId int64
Tnumber string
Drawn string
Designd string
Checked string
Emamined string
Verified string
Approved string
Data string
DesignStage string
Section string
Projec string
Author string
Exist bool
TopicId int64
}
func main() {
test5()
}
func test5() {
// path := "D:/panic.xlsx"
path := "D:/ok.xlsx"
xlFile, _ := xlsx.OpenFile(path) //excelFileName
var catalog Catalog
for _, sheet := range xlFile.Sheets {
for _, row := range sheet.Rows {
j := 1
catalog.Tnumber = row.Cells[j].String()
catalog.Name = row.Cells[j+1].String()
catalog.Drawn = row.Cells[j+2].String()
catalog.Designd = row.Cells[j+3].String()
catalog.Checked = row.Cells[j+4].String()
catalog.Emamined = row.Cells[j+5].String()
catalog.Verified = row.Cells[j+6].String()
catalog.Approved = row.Cells[j+7].String()
catalog.Data = row.Cells[j+8].String()
catalog.DesignStage = row.Cells[j+9].String()
catalog.Section = row.Cells[j+10].String()
catalog.Projec = row.Cells[j+11].String()
fmt.Printf("%s\n", catalog)
}
}
}
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0x849fe0, 0xc082008060)
D:/Go/src/runtime/panic.go:464 +0x3f4
main.test5()
D:/gowork/src/test_go/excel.go:146 +0x83e
main.main()
D:/gowork/src/test_go/excel.go:35 +0x1b
the panic file:panic.xlsx
the ok file:ok.xlsx
摸索了好久,终于搞明白了它的原理:http://www.golangtc.com/t/56ec0d39b09ecc66b9000122
tealeg/xlsx它这个包很奇怪,用
for _, sheet := range xlFile.Sheets
{
for _, row := range sheet.Rows
{
for m, cell := range row.Cells
{
这样的形式获取已经使用了的单元格区间,
如上图,D1单元格不填数据,那么,第一行空行就走不下去。D1单元格填了数据,有时候1~4行row.Cells的长度都是4,有时候仅仅第一行的row.Cells的长度是4,下面2~4行的row.Cells的长度是2。有时候单元格都是空,但调整了大小,它也认为是使用了的区间。有时候第一行的第10列填个数字,那么下面的几行都认为使用到了10列。
对于下面这样获取单元格值的写法——没有进行row.Cells区间判断,会出错:单元格为空,那么就可能row.Cellsindex超界。按常规想法,单元格为空,row.Cells4.String()返回空值就好了嘛,还要一个个去判断?
for _, sheet := range xlFile.Sheets
{
for _, row := range sheet.Rows
{
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有