Go解析Excel异常

在使用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中某些列确实可以为空,如何规避这个问题?


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 := ""
        columnB := ""
        columnC := ""

        if len(row.Cells) >= 1 {
            columnA = row.Cells[0].Value
        }
        if len(row.Cells) >= 2 {
            columnB = row.Cells[1].Value
        }
        if len(row.Cells) >= 3 {
            columnC = row.Cells[2].Value
        }
        fmt.Printf("A列:%s, B列:%s, C列:%s\n", columnA, columnB, columnC)
    }
}

哥们,上面的可以参考参考看看能不能满足要求

参考这篇试试:

【以下回答由 GPT 生成】

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 := ""
        if len(row.Cells) > 0 {
            columnA = row.Cells[0].Value
        }
        columnB := ""
        if len(row.Cells) > 1 {
            columnB = row.Cells[1].Value
        }
        columnC := ""
        if len(row.Cells) > 2 {
            columnC = row.Cells[2].Value
        }

        fmt.Printf("A列:%s, B列:%s, C列:%s\n", columnA, columnB, columnC)
    }
}

对于可能为空的列,我们在获取其值前先进行判断当前行的Cells切片长度是否大于索引值,如果大于则获取对应值,否则赋予一个空字符串。这样可以避免报“out of index”索引错误的问题。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^