2012年1月31日 星期二

VB.net存取Excel


網路上面多半使用ADO來存取Excel,但是個人覺得這種方式蠻不友善的.
尤其對於已經熟悉VBA的人來說,
能用VBA中的物件模型及概念應用在.net中來存取Excel才是真正的王道啊~

在下面的範例中就是使用Excel的核心來存取資料:

'範例
Imports Microsoft.Office.Interop.Excel
Public Sub 存取Excel()

Dim oExcel As Excel.ApplicationClass
Dim oBook As Excel.WorkbookClass
Dim oBooks As Excel.Workbooks
Dim oSheet As Excel.Worksheet

Try
'建立Excel物件並開啟C:\01.xls中的Sheet1
oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oBooks = oExcel.Workbooks
oBook = oBooks.Open("C:\01.xls")
oSheet = oBook.Worksheets("Sheet1")

'寫入資料至Sheet1中的A1儲存格
oSheet.Cells(1, 1).value = "Test"

'讀取Sheet1中的A1儲存格
Dim test As String
test = oSheet.Cells(1, 1).value.ToString


'關閉並釋放Excel物件
oBook.Close(False)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
oBook = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks)
oBooks = Nothing
oExcel.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
oExcel = Nothing
Catch ex As Exception

End Try

End Sub

沒有留言:

張貼留言