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.displayalerts = 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 deallocate everything
 oexcel.quit()
 releasecomobject(ocells) : releasecomobject(osheet)
 releasecomobject(osheets) : releasecomobject(obook)
 releasecomobject(obooks) : releasecomobject(oexcel)
 oexcel = nothing : obooks = nothing : obook = 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.itemarray
 for icol = 0 to ubound(ary)
 ocells(irow + 3, icol + 1) = ary(icol).tostring
 response.write(ary(icol).tostring & vbtab)
 next
 next
end function
新闻热点
疑难解答
图片精选