You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ClosedXML代码报错BC32023:IXLRow非集合类型无法遍历

问题解决:ClosedXML报错BC32023 Expression is of type 'IXLRow', which is not a collection type

错误原因

IXLRow本身不是可枚举的集合类型,无法直接用For Each遍历。必须遍历该行的单元格集合,比如CellsUsed()(仅遍历有数据的单元格)或Cells(遍历所有单元格)。

修复后的完整代码

Public Shared Function ImportExceltoDataTable(filePath As String)
    Try
        Using wb As New XLWorkbook(filePath)
            Form1.ToolStripProgressBar1.Value = 0
            Dim wsByName As IXLWorksheet = wb.Worksheet("ADRES") ' 按名称获取工作表

            Dim dtADRES As New System.Data.DataTable

            ' 从工作表第一行添加列标题
            Dim firstRow As IXLRow = wsByName.Rows(1)
            ' 修复:遍历firstRow的CellsUsed()集合,而非直接遍历firstRow
            For Each cell As IXLCell In firstRow.CellsUsed()
                dtADRES.Columns.Add(cell.Value.ToString())
            Next

            ' 将剩余行数据添加到DataTable
            For Each row As IXLRow In wsByName.RowsUsed().Skip(1)
                Dim dataRow As DataRow = dtADRES.NewRow()
                For i As Integer = 0 To dtADRES.Columns.Count - 1
                    dataRow(i) = row.Cell(i + 1).Value
                Next
                dtADRES.Rows.Add(dataRow)
            Next

            ' 输出DataTable信息(修复原代码的格式错误)
            Console.WriteLine("DataTable contains {0} rows and {1} columns.", dtADRES.Rows.Count, dtADRES.Columns.Count)
            For Each row As DataRow In dtADRES.Rows
                Console.WriteLine(String.Join(", ", row.ItemArray))
            Next

            Form1.DataGridView1.DataSource = dtADRES
            Form1.DataGridView1.AutoResizeColumns()

            Form1.ToolStripProgressBar1.Value = 100
            Form1.ToolStripStatusLabel1.Text = "Klaar, de spreadsheet is ingelezen!"
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Function

额外优化说明

  1. 规范Using块:原代码先声明wb再放入Using的写法改为直接在Using中初始化,同时移除手动调用的wb.Dispose()——Using块会自动释放资源。
  2. 修复输出错误:原代码Console.WriteLine("{0}")缺少参数,改为String.Join(", ", row.ItemArray)可正常输出每行数据。
  3. 移除冗余判断:原代码中If firstRow.CellsUsed().Count > 0 Then的判断多余,因为CellsUsed()本身仅返回有数据的单元格,直接遍历即可。

内容的提问来源于stack exchange,提问作者joska paszli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:42:42