Thao tác với Excel bằng VB.NET

Để thao tác với Excel, bạn vào Reference tìm và tích chọn thư viện Microsoft Excel xx.x object library.
Cách đơn giản nhất là:
Mã:
Imports Microsoft.Office.Interop
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ex As New Excel.Application
        Dim sh As Excel.Worksheet
        Dim wb As Excel.Workbook
        'Open file Excel
        wb = ex.Workbooks.Open(“C:\work\test1.xlsx”)
        sh = wb.Sheets(“THVBA”)
        MsgBox(sh.Range(“B2”).Value)
        ex.Quit()


    End Sub
End Class
Phương pháp chuẩn quy cách :
Mã:
Imports Microsoft.Office.Interop
Public Class Form1

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim xlApp As Excel.Application = Nothing

        Dim xlBook As Excel.Workbook = Nothing
        Dim xlSheet As Excel.Worksheet = Nothing

        Dim xlBookWrite As Excel.Workbook = Nothing
        Dim xlSheetWrite As Excel.Worksheet = Nothing

        Try
            'Nếu Excel đã được khởi động rồi:
            xlApp = GetObject(, "Excel.Application")

        Catch ex As Exception

            'Nếu Excel chưa được khởi động :
            xlApp = CreateObject("Excel.Application")

        End Try

        xlApp.Visible = True
        xlBook = xlApp.Workbooks.Open(“C:\work\test1.xlsx”)
        xlSheet = xlBook.Sheets(“THVBA”)
        'MsgBox(xlSheet.Range(“B2”).Value)



        xlSheet.Cells(1, 1).Value = "APP_Name"

        xlBook.Save()
        xlSheet.Close(False)


        MRComObject(xlSheet)
        MRComObject(xlBook)

        xlApp.Quit()
        MRComObject(xlApp)

        xlSheet = Nothing
        xlBook = Nothing

        xlApp = Nothing
    End Sub
    Private Sub MRComObject(ByVal objCom As Object) '

        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(objCom)
        Catch ex As Exception
            objCom = Nothing
        Finally
            objCom = Nothing
        End Try

    End Sub
End Class
Nguồn :
Mã:
https://itecjapan.xsrv.jp/2020/02/15/vb-net-excel%E3%81%AE%E6%93%8D%E4%BD%9C%E3%80%80%E3%81%9D%E3%81%AE1/
 
Top