Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim mySQL As String = "SELECT * FROM tblData"
Dim conn As New ADODB.Connection()
Dim rs As ADODB.Recordset
Me.Cursor = Cursors.WaitCursor
conn.Open("Provider=Microsoft.Jet.OLEDB.4.0;" & " data source=" & Application.StartupPath & "\Database.mdb")
conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs = conn.Execute(mySQL, , ADODB.CommandTypeEnum.adCmdText)
If rs.RecordCount = 0 Then
MsgBox("Không có dữ liệu nào để xuất!", vbCritical)
Else
Try
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.open(Application.StartupPath & "\Temp.xlt")
oSheet = oBook.Worksheets(1)
With oSheet
.Range("A6").CopyFromRecordset(rs)
.Range("A3") = "BẢNG XUẤT RA"
.Range("A5:B" & .Range("B65000").End(3).Row).Borders.LineStyle = 1
End With
oSheet = Nothing
oBook = Nothing
MsgBox("Đã xuất xong dữ liệu sang file Excel.", vbExclamation, "Xuất dữ liệu")
oExcel.Visible = True
oExcel = Nothing
dt.Dispose()
da.Dispose()
rs.Close()
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
Me.Cursor = Cursors.Default
End Sub
End Class