使用DataGrid或GridView將資料匯出至Excel或Word的方法,
DataGridinOffice.aspx 畫面如下:
DataGridinOffice.aspx.vb 後置程式碼如下:
'//DataGrid匯出Excel Word範例// Partial Public Class DataGridinOffice #Region "按鍵事件處理" Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Inherits System.Web.UI.Page
#Region "自定義方法"
'刷新DataGrid
Private Sub DBInit()
Dim myODB As New testDB
Dim ds As DataSet
ds = myODB.gettestObjs()
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
'匯出Excel方法
Private Sub toExcel()
export("BIG5", "Excel_Fill.xls", "application/vnd.ms-excel")
End Sub
'匯出Word方法
Private Sub toWord()
export("BIG5", "Word_Fill.doc", "application/vnd.ms-word")
End Sub
'匯出事件
Private Sub export(ByVal Encodeing As String, ByVal FileName As String, ByVal ContentType As String)
If DataGrid1.AllowPaging = True Then
DataGrid1.AllowPaging = False
DBInit()
End If
Response.Clear()
Response.Buffer = True
Response.Charset = Encodeing
'儲存的檔名
Response.AppendHeader("Content-Disposition", "attachment; filename=" & FileName)
'編碼與字元集
Response.ContentEncoding = Encoding.GetEncoding(Encodeing)
Response.ContentType = ContentType
DataGrid1.EnableViewState = False
Dim SW As New System.IO.StringWriter
Dim HW As New System.Web.UI.HtmlTextWriter(SW)
DataGrid1.RenderControl(HW)
Response.Write(SW.ToString())
Response.End()
If DataGrid1.AllowPaging = False Then
DataGrid1.AllowPaging = True
DBInit()
End If
End Sub
#End Region
Private Sub btnExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcel.Click
toExcel()
End Sub
Private Sub btnWord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWord.Click
toWord()
End Sub
#End Region
'防止出現「必須有runat=server的表單標記之中」錯誤
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
End Sub
'分頁
Private Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged
DataGrid1.CurrentPageIndex = e.NewPageIndex
DBInit()
End Sub
If Not IsPostBack Then
DBInit()
End If
End Sub
End Class
留言列表