在使用go语言"github.com/tealeg/xlsx"库进行解析Excel文件时,文件有A、B、C三列,根据下面代码按行解析:
func main() {
excelFileName := "D:\\test.xlsx"
// 通过 xlsx.OpenFile 函数打开 Excel 文件
xlFile, err := xlsx.OpenFile(excelFileName)
if err != nil {
fmt.Printf("打开 Excel 文件出错:%s\n", err)
return
}
sheet := xlFile.Sheets[0]
for _, row := range sheet.Rows {
// 检查当前行是否为空行
if len(row.Cells) == 0 {
continue
}
// 获取当前行的 A、B、C 列数据
columnA := row.Cells[0].Value
columnB := row.Cells[1].Value
columnC := row.Cells[2].Value
fmt.Printf("A列:%s, B列:%s, C列:%s\n", columnA, columnB, columnC)
}
}
但是当某一行的A列数据为空时,程序会报“out of index”索引错误,将数据输出才发现,在Excel中,该行A列为空,当程序中将B列的数据进行了前移,作为A列的数据,导致在解析的过程中Cells切片只有两列数据。如果Excel中某些列确实可以为空,如何规避这个问题?