在ASP.NET中将数据直接输出成Excel内容 (转)[@more@]
在ASP.NET中将数据直接输出成excel内容
本文实现了将数据库中的数据直接输出到Excel文件格式并在浏览器里输出。下面就是实现的例子:
dotnetplayground.com/Exam/Data2ExcelDemo.htm" target=_target>查看例子
ExcelExport.aspx
web.mengxianhui.com.ExcelExport"%>
w3c//DTD HTML 4.0 Transitional//EN">
ExcelExport
microsoft Visual Studio.NET 7.0">
Visual Basic 7.0">
Javascript">
intellisense/IE5">
RM id="Form1" method="post" runat="server">
selectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66">
ExcelExport.aspx.vb
Public Class ExcelExport
Inherits System.Web.UI.Page
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
#Region " Web 窗体设计器生成的代码 "
'该调用是 Web 窗体设计器所必需的。
buggerStepThrough()> 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
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10748419/viewspace-988555/
,如需转载,请注明出处,否则将追究法律责任。