Programming Tutorials

Create an Excel 2007 file in VB.NET 2005

By: Issac in VB.net Tutorials on 2009-01-31  

Excel file can be automated or worked upon by Auomation to Excel 2007,It can be done in two ways through Excel Object Model and using Microsoft Jet Engine to connect to Excel, through this we can achieve creating new wokbook add data to it or create charts in it, For creating an Excel 2007 worksheet in VB.NET 2005 , 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.

1. Create a new project and add a button to the Form.

Select reference dialouge from Project menu 

excel_reference.jpg


Select Microsoft Excel 12.0 Object Library and click OK button 


excel_library.jpg
Now you can start coding to create a new Excel file.

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

In the code, Imports Excel = Microsoft.Office.Interop.Excel - we assign the excel reference to a variable called Excel. 
When you execute this program, the file created in the c:\ of your system.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in VB.net )

Latest Articles (in VB.net)