Tuesday, 28 August 2012

VB.NET - How to creae Excel file - Simple example


1. Create new project
2. Add reference




     
3. Select Microsoft.Office.Interop.Excel - ensure Excel is installed.


4. Copy the following code - this will create simple Excel file in your C:\Temp\ExcelTest directory

Dim fileTest As String = "C:\Temp\ExcelTest\test.xlsx"
        If File.Exists(fileTest) Then
            File.Delete(fileTest)
        End If

        Dim oExcel As Object
        oExcel = CreateObject("Excel.Application")
        Dim oBook As Excel.Workbook
        Dim oSheet As Excel.Worksheet

        oBook = oExcel.Workbooks.Add
        oSheet = oExcel.Worksheets(1)

        oSheet.Name = "Test Name"
        oSheet.Range("A1").Value = "SOME VALUE"
        oBook.SaveAs(fileTest)
        oBook.Close()
        oBook = Nothing
        oExcel.Quit()
        oExcel = Nothing

5. More info on this video:

6 comments:

  1. Hi Publisher,

    I follow your way, but I got "Cannot create ActiveX component." Error. I got this error, when the code is trying to create:
    Dim oExcel As Object
    oExcel = CreateObject("Excel.Application")

    Can you help me to solve this?

    thx.

    ReplyDelete
    Replies
    1. This comment has been removed by a blog administrator.

      Delete
  2. Do you have excel installed on your computer?

    ReplyDelete
    Replies
    1. This comment has been removed by a blog administrator.

      Delete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. For 2017 VB users:

    Project>Add Reference> COM > Type Libraries

    ReplyDelete