Friday 4 January 2013

Create an Excel file in VB.NET


From the following sections you can find how to create an Excel worksheet through VB.NET . For creating an Excel worksheet in VB.NET , you have to add the Microsoft Excel 12.0 Object Library in you project.

From the following pictures to show how to add Excel reference library in your project.


Step1:
     Create a new project and add a button to the Form.
     Select reference dialouge from Project menu



 Step2:
    Select Microsoft Excel 12.0 Object Library and click OK button
Step3:
    Now you can start coding to create a new Excel file.
For example like this code 



Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object,_
  ByVal e As System.EventArgs) Handles Button1.Click

        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")
        xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
        xlWorkSheet.SaveAs("C:\vbexcel.xlsx")

        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        MsgBox("Excel file created , you can find the file c:\")
    End Sub

    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

End Class
output of the program: In the code , Imports Excel = Microsoft.Office.Interop.Excel - we assign the excel reference to a vatriable Excel. When you execute this program , the file created in the c:\ of your computer .

No comments:

Post a Comment