INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

How-to

How to export to Excel from vb.net code. by Sorwen
Posted: 26 Sep 07

I see this question a lot and was rather surprised there wasn't a how to.  This is the most effective manner I've found to export to excel without excessive code or getting someone's dll/plug-in/etc.  Some people don't like it because it uses adodb rather than ado.net.

CODE

Public Shared Sub DataToExcel(ByVal rTable As ADODB.Recordset, ByVal WorkbookLocation As String, ByVal WorkbookName As String)
        Dim oExcel As Object
        Dim oBook As Object
        Dim oSheet As Object
        
        oExcel = CreateObject("Excel.Application")
        oBook = oExcel.Workbooks.Add
        oSheet = oBook.Worksheets(1)
      
        rTable.Open()
        oSheet.Range("A1").CopyFromRecordset(rTable)
        rTable.Close()

        oBook.SaveAs(WorkbookLocation & WorkbookName)

        oSheet = Nothing
        oBook = Nothing
        oExcel.Quit()
        oExcel = Nothing
        GC.Collect()
    End Sub

This is the total basics.  There are all kinds of modifications you could do.  In this format you can send it any commands that you would as if you were working in a Excel workbook's VBA.

Auto Format all cells width:

CODE

        oSheet.Cells.Select()
        oSheet.Cells.EntireColumn.AutoFit()

Force save without overwrite confirmation:

CODE

            oExcel.DisplayAlerts = False
            oBook.SaveAs(WorkbookLocation & WorkbookName)
            oExcel.DisplayAlerts = True

Back to Visual Basic (Microsoft) VB.NET FAQ Index
Back to Visual Basic (Microsoft) VB.NET Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close