Click here to Skip to main content
15,921,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you save listview items to Microsoft Office Excel 2007?
Also how can you read it back from excel to ListView?
Posted

1 solution

How to write some data to Excel?
For example like this:
VB
Dim r As Integer = 0, c As Integer = 0
Dim oExcel As Object = Nothing, oWbk As Object = Nothing, oWsh As Object = Nothing, oRng As Object = Nothing
'using late bounds
Try
    'create Excel application object
    oExcel = CreateObject("Excel.Application")
    'add new empty workbook and set oWbk variable as obcject variable; type: Workbook
    oWbk = oExcel.Workbooks.Add()
    'set oWsh variable as object variable; type: WorkSheet (not Sheet!)
    oWsh = oWbk.Worksheets(1)
    'save 10 items to Excel
    'single column ListView
    'For r = 0 To 9
    '    oRng = oWsh.Range(CStr("A" & r + 1))
    '    oRng.Value = "Item " & r.ToString
    'Next
    'in case of multiple columns ListView
    For c = 0 To 9
        For r = 0 To 9
            oRng = oWsh.Cells(r + 1, c + 1)
            oRng.Value = "Row " & r.ToString & " Column " & c.ToString
        Next
    Next

Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error!")

Finally
    'clear variables ;)
    oWsh = Nothing
    oWbk = Nothing
    'when you create instance of Excel application, show Excel
    If Not oExcel Is Nothing Then oExcel.Visible = True
    oExcel = Nothing

End Try


To read Excel file you need to know a file name and worksheet name.
Changing 1 line, you can set oWbk variable to existing Excel file:
oWbk = oExcel.Workbooks.Open(sFileName)

sFileName should be a full path of existing Excel file, for example:
sFileName = "D:\MyFavoritesFiles\example1.xls"
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900