如何将Listview项目保存到Microsoft Office Excel 2007
问题描述:
如何将列表视图项保存到Microsoft Office Excel 2007?
另外,如何从excel读取它到ListView?
How do you save listview items to Microsoft Office Excel 2007?
Also how can you read it back from excel to ListView?
答
如何将数据写入Excel?
例如这样的:
How to write some data to Excel?
For example like this:
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
要读取Excel文件,您需要知道文件名和工作表名称.
更改1行,您可以将oWbk变量设置为现有的Excel文件:
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 应该是现有Excel文件的完整路径,例如:
sFileName should be a full path of existing Excel file, for example:
sFileName = "D:\MyFavoritesFiles\example1.xls"