Create an Excel File from Visual Basic

April 25th, 2007

Creating and working with Excel files from Visual Basic is very easy. To demonstrate, let's create a very simple console application that will create an excel workbook, "HelloWorld.xls". In Sheet1!A1 of the workbook, we'll put the words "Hello, World".

Here's how.

1. In Visual Basic 2005 Express, create a new console application.

2. Add a reference to the Microsoft Excel Object Library.
Add a reference to the Microsoft Excel Object Library

3. Put the code.

Imports Microsoft.Office.Interop
Imports System.IO
Module Module1

    Sub Main()
        Dim xlApp As New Excel.Application
        Dim xlWb As Excel.Workbook
        Dim strFileName As String
        xlWb = xlApp.Workbooks.Add
        xlWb.Worksheets(1).Range("A1").Value = "Hello, World"
        strFileName = My.Application.Info.DirectoryPath & "\HelloWorld.xls"
        If File.Exists(strFileName) Then
            If vbNo = MsgBox(strFileName & " already exists. Overwrite?", MsgBoxStyle.Question & MsgBoxStyle.YesNo) Then
                xlWb.Close(False)
                xlApp.Quit()
                Exit Sub
            End If
        End If
        xlApp.DisplayAlerts = False
        xlWb.SaveAs(My.Application.Info.DirectoryPath & "\HelloWorld.xls")
        xlApp.DisplayAlerts = True

        xlWb.Close(False)
        xlApp.Quit()
    End Sub

End Module

You can download the sample project here .

Posted in Excel, How To, Visual Basic | No Comments




No Comments yet »

RSS feed for comments on this post. TrackBack URI

Leave a comment



(C) by Virgilio Adriano. All rights reserved. Powered by WordPress.
Entries and comments feeds.
It took 0.338 seconds to load this page.