NEWS

Export dữ liệu từ SQL Server sang Excel với VB.NET

Export dữ liệu từ SQL Server sang Excel với VB.NET
Đăng bởi: Hoàng Tử Nhỏ - Lượt xem: 20613 21:36:39, 13/10/2015VB.NET   In bài viết

Trong quá trình thiết kế chương trình đôi lúc người sử dụng cần dùng file Excel để làm công việc gì đó mà các biểu mẫu report được thiết kế kèm theo sẽ không đáp ứng được.

Bài viết này mình sẽ hướng dẫn các bạn cách export dữ liệu ra file Excel từ SQL với VB.NET như thế nào?

Export SQL to Excel với VB.NET

Để sử dụng các thư viên của Excel các bạn nhớ import thư viện này vào nha:

Imports Microsoft.Office.Interop

- Trước tiên bạn load dữ liệu vào DataGirdView phần này chắc mình không hướng dẫn nha.

- Đến phần quan trọng nhất viết Function xuất dữ liệu ra file Excel

Public Sub ExportToExcel(ByVal dtTemp As DataTable, ByVal filepath As String)
        Dim strFileName As String = filepath
        If System.IO.File.Exists(strFileName) Then
            If (MessageBox.Show("Bạn có muốn chép đè lên file đã tồn tại không?", "Export to Excel", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = System.Windows.Forms.DialogResult.Yes) Then
                System.IO.File.Delete(strFileName)
            Else
                Return
            End If

        End If
        Dim _excel As New Excel.Application
        Dim wBook As Excel.Workbook
        Dim wSheet As Excel.Worksheet

        wBook = _excel.Workbooks.Add()
        wSheet = wBook.ActiveSheet()

        Dim dt As System.Data.DataTable = dtTemp
        Dim dc As System.Data.DataColumn
        Dim dr As System.Data.DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0

        ' export the Columns 
        '  If CheckBox1.Checked Then
        For Each dc In dt.Columns
            colIndex = colIndex + 1
            wSheet.Cells(1, colIndex) = dc.ColumnName
        Next
        ' End If

        'export the rows 
        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
                wSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
            Next
        Next
        wSheet.Columns.AutoFit()
        wBook.SaveAs(strFileName)

        'release the objects
        ReleaseObject(wSheet)
        wBook.Close(False)
        ReleaseObject(wBook)
        _excel.Quit()
        ReleaseObject(_excel)
        ' some time Office application does not quit after automation: so i am calling GC.Collect method.
        GC.Collect()

End Sub
Private Sub ReleaseObject(ByVal o As Object)
        Try
            While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
            End While
        Catch
        Finally
            o = Nothing
        End Try
    End Sub

- Kế tiếp load dữ liệu từ SQL vào DataTable

Function GetDatatable(strLenh As String) As DataTable
        'Create the data table at runtime
        Dim dt As New DataTable
        Dim ds As New DataSet
        ds = _load_data(strLenh)
        dt = ds.Tables(0)
        Return dt
End Function

- Đến bước này xem như mọi thư đã chuẩn bị xong, cơm đã dọn lên rồi nhưng bây giờ dùng như thế nào đây. Tại nút "Export to Excel" ta viết như sau:

      SaveFileDialog1.Filter = "Excel files |*.xlsx"
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim strLenh As String = "select * from tbl_user"
            ExportToExcel(GetDatatable(strLenh), SaveFileDialog1.FileName)
            System.Diagnostics.Process.Start(SaveFileDialog1.FileName)
        End If

Thế là xong. Chúc bạn thành công. Nếu bạn thấy bài viết hay thì comment động viên nha hoặc share bài biết. 

Download Project

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

Export dữ liệu từ SQL Server sang Excel với VB.NET
Đăng bởi: Hoàng Tử Nhỏ - Lượt xem: 20613 21:36:39, 13/10/2015VB.NET   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp