Wednesday, 5 September 2012

VB.NET - Excel - How to create Excel file with multiple worksheets

        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

        ' first worksheet
        If oExcel.Application.Sheets.Count() < 1 Then
            oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
        Else
            oSheet = oExcel.Worksheets(1)
        End If
        oSheet.Name = "one"
        oSheet.Range("B1").Value = "First One"

        ' second
        If oExcel.Application.Sheets.Count() < 2 Then
            oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
        Else
            oSheet = oExcel.Worksheets(2)
        End If
        oSheet.Name = "two"
        oSheet.Range("B1").Value = "Second one"

        ' third
        If oExcel.Application.Sheets.Count() < 3 Then
            oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
        Else
            oSheet = oExcel.Worksheets(3)
        End If
        oSheet.Name = "three"
        oSheet.Range("B1").Value = "Thrid"

        ' next
        If oExcel.Application.Sheets.Count() < 4 Then
            oSheet = CType(oBook.Worksheets.Add(), Excel.Worksheet)
        Else
            oSheet = oExcel.Worksheets(4)
        End If
        oSheet.Name = "four"
        oSheet.Range("B1").Value = "Four"

        ' by default this worksheet will be placed in front of the first
        ' the code below will move it after third one

        oSheet.Move(After:=oBook.Worksheets(oBook.Worksheets.Count))

        oBook.SaveAs(fileTest)
        oBook.Close()
        oBook = Nothing

Same example on YouTube

No comments:

Post a Comment