Rabeea Qabaha Rabeea Qabaha - 5 months ago 59
Vb.net Question

export the listview items to excel sheet with listview header

i have this code to export the data in listview to excel sheet ,,,, but this code export data without the header of list view ... how i can edit this code to show header of the listview . thanks a lot .


Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xslx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
'create objects to interface to Excel
Dim xls As New Excel.Application
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
'create a workbook and get reference to first worksheet
xls.Workbooks.Add()
book = xls.ActiveWorkbook
sheet = book.ActiveSheet
'step through rows and columns and copy data to worksheet
Dim row As Integer = 1
Dim col As Integer = 1
For Each item As ListViewItem In ListView1.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
'save the workbook and clean up
book.SaveAs(SaveFileDialog1.FileName)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(book)
releaseObject(xls)
End Sub

Private Sub releaseObject(ByVal obj As Object)
'Release an automation object
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub


Answer

You can get each column text by using this code:

Dim columns As New List(Of String)
    Dim columncount As Integer = ListView1.Columns.Count - 1


    For i As Integer = 0 To columncount
        columns.Add(ListView1.Columns(i).Text)
    Next


    For Each columnname In columns
        MessageBox.Show(columnname)
    Next
Comments