为什么此带有 ClosedXML 的代码不起作用:BC32023 表达式的类型为“IXLRow”,它不是集合类型

问题描述 投票:0回答:1

我尝试过自己的大脑和几种人工智能工具,但不知何故,这段带有 ClosedXML 的代码会生成错误:

BC32023 表达式的类型为“IXLRow”,它不是集合类型。

对于每个单元格作为第一行中的 IXLCell

我使用代码的目标是将 Excel 工作表中的表格放入数据表中以进行某些数据分析。虽然这不是最终情况,但我想看看是否可以将数据复制到数据网格中。但上述错误很难绕过。有什么想法为什么这行不通吗?


`公共共享函数 ImportExceltoDataTable(filePath As String) Dim wb As XLWorkbook = New XLWorkbook(filePath) 尝试 使用白平衡 Form1.ToolStripProgressBar1.Value = 0 Dim wsByName As IXLWorksheet = wb.Worksheet("ADRES") ' 按名称访问工作表

            Dim dtADRES As New System.Data.DataTable

            'Add Columns from the first row of the worksheet
            Dim firstRow As IXLRow = wsByName.Rows(1)
            **For Each cell As IXLCell In firstRow**
                If firstRow.CellsUsed().Count > 0 Then
                    dtADRES.Columns.Add(cell.Value.ToString())
                End If
            Next

            ' Add data from the remaining rows to the 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

            ' Use the DataTable as needed
            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("{0}")
            Next

            wb.Dispose()



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

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

我尝试了几个代码示例,但总的来说,存在一些与同一错误相关的错误。我广泛尝试了 ChatGPT 和 Gemini,但没有成功。我确保工作表的标题包含有效的单元格值来充当列标题。

closedxml
1个回答
0
投票

如错误消息所示,

firstRow
不是集合类型,您无法枚举它。

而是根据您的要求枚举

firstRow.Cells()
firstRow.CellsUsed()
。前者将枚举该行中的所有单元格(即使它们为空),后者将仅枚举具有内容、样式或公式的单元格。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.