public class excelexport inherits system.web.ui.page protected withevents datagrid1 as system.web.ui.webcontrols.datagrid #region " web 窗体设计器生成的代码 " '该调用是 web 窗体设计器所必需的。 <system.diagnostics.debuggerstepthrough()> private sub initializecomponent() end sub
private sub page_init(byval sender as system.object, byval e as system.eventargs) _ handles mybase.init 'codegen: 此方法调用是 web 窗体设计器所必需的 '不要使用代码编辑器修改它。 initializecomponent() end sub
#end region private sub page_load(byval sender as system.object, byval e as system.eventargs) _ handles mybase.load '在此处放置初始化页的用户代码 ' 定义是否是 sql server 数据库,这里为false dim blnissqlserver as system.boolean = false dim strsql as string dim objdataset as new dataset() dim objconn as object dim strcnn as string if blnissqlserver then strcnn = "user id=sa;initial catalog=northwind;data source=./netsdk;" objconn = new system.data.sqlclient.sqlconnection(strcnn) objconn.open() dim objadapter as new system.data.sqlclient.sqldataadapter() strsql = "select * from customers where country='usa'" objadapter.selectcommand = new system.data.sqlclient.sqlcommand(strsql, objconn) objadapter.fill(objdataset) else strcnn = "provider=microsoft.jet.oledb.4.0;data source=" + server.mappath("test.mdb") objconn = new system.data.oledb.oledbconnection(strcnn) objconn.open() dim objadapter as new system.data.oledb.oledbdataadapter() strsql = "select top 10 title from document" objadapter.selectcommand = new system.data.oledb.oledbcommand(strsql, objconn) objadapter.fill(objdataset) end if dim oview as new dataview(objdataset.tables(0)) datagrid1.datasource = oview datagrid1.databind() objconn.close() objconn.dispose() objconn = nothing if request.querystring("bexcel") = "1" then response.contenttype = "application/vnd.ms-excel" ' 从content-type header中去除charset设置 response.charset = "" ' 关闭 viewstate me.enableviewstate = false dim tw as new system.io.stringwriter() dim hw as new system.web.ui.htmltextwriter(tw) ' 获取control的html datagrid1.rendercontrol(hw) ' 把html写回浏览器 response.write(tw.tostring()) response.end() end if end sub end class