Imports System.Runtime.InteropServices.Marshal
THEN, REPLACE The Default Page_load Event with the code in Figure 1.
Private sub page_load (byval sender as system.Object, _
BYVAL E as system.eventargs) Handles mybase.load
Dim OEXCEL As New Excel.Application ()
DIM OBOOKS AS Excel.Workbooks, Obook As Excel.Workbook
Dim Osheets as Excel.Sheets, Osheet As Excel.Worksheet
Dim Ocells as Excel.Range
DIM SFILE As String, STEMPLATE AS STRING
DIM DT AS DATATABLE = _
Ctype (Application.Item ("MyDataTable", DataTable)
Sfile = server.mappath (request.applicationpath) & _
"/Myexcel.xls"
STEMPLATE = Server.Mappath (Request.ApplicationPath) &_
"/Mytemplate.xls"
OEXCEL.Visible = false: OEXCEL.DISPLAYALTS = false
'Start a New Workbook
OBOOKS = OEXCEL.WORKBOOKS
OBOOKS.OPEN (Server.Mappath (Request.ApplicationPath) & _
"/Mytemplate.xls") 'load colorful template with chart
Obook = OBOOKS.ITEM (1)
Osheets = OBOOK.WORKSHEETS
Osheet = ctype (Osheets.Item (1), Excel.Worksheet)
Osheet.name = "first sheet"
Ocells = osheet.cells
Dumpdata (DT, Ocells) 'Fill in The Data
Osheet.saveas (sfile) 'Save in a Temporary File
OBOOK.CLOSE ()
'Quit EXCEL AND THOROUGHLY DEATIONOCATE EVERYTHING
OEXCEL.QUIT ()
ReleaseComobject (Ocells): ReleaseComobject (Osheet)
ReleaseComobject (Osheets): ReleaseComobject (OBOOK)
ReleaseComobject (OBOOKS): ReleaseComobject (OEXCEL)
OEXCEL = Nothing: OBOOKS = Nothing: OBOOKS = Nothing: OBOOKS = Nothing
Osheets = Nothing: Osheet = Nothing: Ocells = Nothing
System.gc.collect ()
Response.Redirect (sfile) 'send the user to the file
End Sub
'Outputs a datatable to an excel worksheet
Private function dumpdata (byval _
DT As DataTable, ByVal Ocells as Excel.Range AS String
DIM DR AS DATAROW, ARY () AS Object
DIM IROW AS INTEGER, ICOL AS INTEGER
'Output Column Headers
For icol = 0 to dt.columns.count - 1
Ocells (2, ICOL 1) = dt.columns (icol) .tostring
NEXT
'Output Data
For irow = 0 to dt.rows.count - 1
Dr = dt.rows.Item (irow)
Ary = Dr.Itemmarray
For icol = 0 to ubound (ary)
Ocells (IROW 3, ICOL 1) = ary (icol) .tostring
Response.write (ary (icol) .tostring & vbtab)
NEXT
NEXT
END FUNCTION