将Listview项导出为ex​​cel,使子项不是listviewItem的成员错误

时间:2015-12-09 10:19:44

标签: vb.net excel listview

我目前正在根据用户输入搜索文本框的文本,使用数据库中的数据填充列表视图。

<ListView x:Name="listSearchServer" HorizontalAlignment="Center" Height="282" Margin="20,50,33,0" VerticalAlignment="Top" Width="264" BorderThickness="1" BorderBrush="#FFCCCCCC" Grid.ColumnSpan="3"/>

因此,当我运行SQL并获取所需的数据时,我将这些项添加到listview

While reader.Read()

                countvalues = countvalues + 1

                'Populate the SearchServers listview with result from query

                Dim share = reader("ShareName")
                listSearchServer.Items.Add(share)

            End While

现在我添加了一个按钮,将结果导出到excel,并且我使用了以下代码来恢复错误 - &#34;子项不是listviewitems的成员&#34;

Private Sub cmdExportServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExportServer.Click


    Dim xls As New Excel.Application
    Dim book As Excel.Workbook
    Dim sheet As Excel.Worksheet

    xls.Workbooks.Add()
    book = xls.ActiveWorkbook
    sheet = book.ActiveSheet

    Dim row As Integer = 1
    Dim col As Integer = 1

    For Each item As ListViewItem In listSearchServer.Items

        For i As Integer = 0 To item.SubItems.Count - 1
            sheet.Cells(row, col) = item.SubItems(i).Text
            col = col + 1
        Next
        row += 1
        col = 1
    Next

    xls.Visible = True

    sheet = book.Sheets("Sheet1")

    Me.Close()
End Sub

这是因为我没有子项吗?有谁知道如何将数据导出到Excel。

编辑

Dim row As Integer = 1

    For Each item As String In listSearchServer.Items

        sheet.Cells(row, 1) = item
        row = row + 1
    Next

对于这个例子,我实际上并不需要跨列移动,并且&#34; For Each item作为ListViewItem&#34;被改为&#34;作为String&#34;然后对于每一行,我将listview中的项目分配给excel列行,并在每次正常工作时递增。

感谢@jelly的帮助

0 个答案:

没有答案