2013年10月9日 星期三

VB.net 匯出匯入Excel


1.加入參考Microsoft Office Interop Excel

















2.程式碼
  Imports Excel = Microsoft.Office.Interop.Excel
    Dim app As New Excel.Application

    Dim book As Excel.Workbook

    Dim sheet As Excel.Worksheet

    Dim range As Excel.Range

    Dim FilePath As String


       
        app.DisplayAlerts = False
        app.Visible = False
        '設定執行路徑
        FilePath = "c:\"
        If My.Computer.FileSystem.DirectoryExists(FilePath) = False Then
            My.Computer.FileSystem.CreateDirectory(FilePath)
        End If
        '在程式開始執行路徑取得 test.xls
        'book = app.Workbooks.Open(Application.StartupPath & "c:\test.xls")
        '在執行路徑取得 test.xls
        book = app.Workbooks.Open(FilePath & "\test.xls")
        sheet = book.Sheets(1)
        range = sheet.Cells(1, 1)

        '讀取顯示 Cell(1,1) 值
        MsgBox(range.Value)

        '寫入 Cell(1,1)
        range.Value = "12345"

        '另存檔案到 c:\test1.xls
        book.SaveAs("c:\test1.xls")
        book.Close()
    

沒有留言:

張貼留言