liubayern 2023-08-03 17:39 采纳率: 33.3%
浏览 6

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

  • 写回答

3条回答 默认 最新

  • 不良使 Python领域潜力新星 2023-08-03 17:54
    关注
    
    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)
        }
    }
    

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

    评论

报告相同问题?

问题事件

  • 创建了问题 8月3日

悬赏问题

  • ¥30 arduino vector defined in discarded section `.text' of wiring.c.o (symbol from plugin)
  • ¥20 关于#c++#的问题:(2)运算二叉树·表达式一般由一个运算符和两个操作数组成:(相关搜索:二叉树遍历)
  • ¥20 如何训练大模型在复杂因素组成的系统中求得最优解
  • ¥15 关于#r语言#的问题:在进行倾向性评分匹配时,使用“match it"包提示”错误于eval(family$initialize): y值必需满足0 <= y <= 1“请问在进行PSM时
  • ¥45 求17位带符号原码乘法器verilog代码
  • ¥20 PySide6扩展QLable实现Word一样的图片裁剪框
  • ¥15 matlab数据降噪处理,提高数据的可信度,确保峰值信号的不损失?
  • ¥15 怎么看我在bios每次修改的日志
  • ¥15 python+mysql图书管理系统
  • ¥15 Questasim Error: (vcom-13)