简单解决golang的excelize扩展包修改单元格内容时报错的问题

在对打开的excel进行修改操作时发现程序报错:

panic: runtime error: index out of range
goroutine 1 [running]:
github.com/Luxurioust/excelize.checkCellInArea(0xc0422d68f6, 0x2, 0xc0425a5750, 0x3, 0xc0422d6800)
C:/Users/Administrator/go/src/github.com/Luxurioust/excelize/cell.go:536 +0x387
github.com/Luxurioust/excelize.(*File).mergeCellsParser(0xc0420346c0, 0xc042042640, 0x59ebd5, 0x2, 0xc042925de0, 0x4b2dae)
C:/Users/Administrator/go/src/github.com/Luxurioust/excelize/cell.go:18 +0xc4
github.com/Luxurioust/excelize.(*File).SetCellStr(0xc0420346c0, 0x5a0f0f, 0xc, 0x59ebd5, 0x2, 0x59fa54, 0x6)
C:/Users/Administrator/go/src/github.com/Luxurioust/excelize/cell.go:431 +0x90
github.com/Luxurioust/excelize.(*File).SetCellValue(0xc0420346c0, 0x5a0f0f, 0xc, 0x59ebd5, 0x2, 0x562500, 0x5c3aa0)
C:/Users/Administrator/go/src/github.com/Luxurioust/excelize/cell.go:57 +0x657

错误信息已经定位得非常明确了,很显然是数组越界,找到对应的方法checkCellInArea其中

func checkCellInArea(cell, area string) bool {
	cell = strings.ToUpper(cell)
	area = strings.ToUpper(area)

	ref := strings.Split(area, ":")
	from := ref[0]
	to := ref[1]//问题出现在这里!!!

	col, row := getCellColRow(cell)
	fromCol, fromRow := getCellColRow(from)
	toCol, toRow := getCellColRow(to)

	return axisLowerOrEqualThan(fromCol, col) && axisLowerOrEqualThan(col, toCol) && axisLowerOrEqualThan(fromRow, row) && axisLowerOrEqualThan(row, toRow)
}

ref[1]并不存在,而引发该问题的根本原因是传入的参数area有问题,再看一下调用该方法的地方:

func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
	axis = strings.ToUpper(axis)
	if xlsx.MergeCells != nil {
		for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
			if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
				axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
			}
		}
	}
	return axis
}

根源就在这里:xlsx.MergeCells.Cells这个数组的内容本应该是所有合并的单元格,但在处理我给的excel时却发现了并未合并的单元格,也就是说最最根源问题是在xlsx.MergeCells.Cells的处理上。

该问题我已经提交给了excelize项目组成员,修改方案让他们来决定吧。

不过我们可以先简单处理一下,只要在数组越界的地方做一个判断即可:

func checkCellInArea(cell, area string) bool {
	cell = strings.ToUpper(cell)
	area = strings.ToUpper(area)

	ref := strings.Split(area, ":")
	if len(ref) < 2 {//我添加的代码
		return false//我添加的代码
	}//我添加的代码
	from := ref[0]
	to := ref[1]

	col, row := getCellColRow(cell)
	fromCol, fromRow := getCellColRow(from)
	toCol, toRow := getCellColRow(to)

	return axisLowerOrEqualThan(fromCol, col) && axisLowerOrEqualThan(col, toCol) && axisLowerOrEqualThan(fromRow, row) && axisLowerOrEqualThan(row, toRow)
}

你可能感兴趣的:(简单解决golang的excelize扩展包修改单元格内容时报错的问题)