You are hereCreate an Excel 2003 Workbook Using VB.Net


Create an Excel 2003 Workbook Using VB.Net


By hagrin - Posted on 04 August 2008

The following contains code on "How to Create an Excel 2003 Workbook Using VB.Net". Remember, you will need to add the "Import Microsoft.Office.Interop" reference at the top of your code. In addition, you will need sufficient rights to create files in your desired save location as well as Office installed on the machine hosting the application.

Dim MyEx As New Excel.Application
Dim MyBook As Excel.Workbook
Dim MySheet As Excel.Worksheet
MyEx.DisplayAlerts = False
MyBook = MyEx.Workbooks.Add
MySheet = MyBook.Sheets.Add
MySheet.Name = "Worksheet Name"

'Entering static values into cells as headers
MySheet.Cells(1, 1) = "Header 1"
MySheet.Cells(1, 2) = "Header 2"
MySheet.Cells(1, 3) = "Header 3"
MySheet.Cells(1, 4) = "Header 4"
MySheet.Cells(1, 5) = "Header 5"
MySheet.Cells(1, 6) = "Header 6"

'Reading through a data set to fill in the rest of the worksheet
For i = 0 To DataSet.Tables(0).Rows.Count - 1
   MySheet.Cells(i + 2, 1) = DataSet.Tables(0).Rows(i).Item(0)
   MySheet.Cells(i + 2, 2) = DataSet.Tables(0).Rows(i).Item(1)
   MySheet.Cells(i + 2, 3) = DataSet.Tables(0).Rows(i).Item(2)
   MySheet.Cells(i + 2, 4) = DataSet.Tables(0).Rows(i).Item(3)
   MySheet.Cells(i + 2, 5) = DataSet.Tables(0).Rows(i).Item(4)
   MySheet.Cells(i + 2, 6) = DataSet.Tables(0).Rows(i).Item(5)
Next

MyBook.SaveAs("FileName.csv", FileFormat:=Excel.XlFileFormat.xlCSV)
MyBook.Close()
MyEx.Quit()
MySheet = Nothing
MyBook = Nothing
MyEx = Nothing
System.GC.Collect()