2009年4月25日 星期六

擴展 GridView 控制項 加入匯出 Excel & Word 功能

擴展 GridView 控制項 加入匯出 Excel & 匯出 Word

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Drawing

Namespace WebControls
< _
Description("TBGridView 控制項"), _
ToolboxData("<{0}:TBGridView runat=server>") _
> _
Public Class TBGridView
Inherits GridView

'''
''' GridView 控制項匯出 Excel 文件。
'''

Public Sub ExportExcel()
Export(Encoding.UTF8, "gridview.xls", "application/ms-excel")
End Sub

'''
''' GridView 控制項匯出 Word 文件。
'''

Public Sub ExportWord()
Export(Encoding.UTF8, "gridview.doc", "application/ms-word")
End Sub

'''
''' GridView 控制項匯出。
'''

''' 編碼方式。
''' 檔案名稱。
''' 內容類型標頭。
Public Sub Export(ByVal Encoding As Encoding, ByVal FileName As String, ByVal ContentType As String)
Dim oResponse As HttpResponse
Dim oStringWriter As System.IO.StringWriter
Dim oHtmlWriter As System.Web.UI.HtmlTextWriter
Dim bAllowPaging As Boolean
Dim sText As String
Dim sFileName As String

If TypeOf Me.Page Is TBBasePage Then
DirectCast(Me.Page, TBBasePage).IsVerifyRender = False '頁面不需驗證控制項
End If

'檔案名稱需經 UrlEncode 編碼,解決中文檔名的問題
sFileName = HttpUtility.UrlEncode(FileName, Encoding)

oResponse = HttpContext.Current.Response
oResponse.Clear()
sText = "<meta http-equiv='Content-Type'; content='text/html';charset='{0}'>"
sText = String.Format(sText, Encoding.WebName)
oResponse.Write(sText)
oResponse.AddHeader("content-disposition", "attachment;filename=" & sFileName)
oResponse.ContentEncoding = Encoding
oResponse.Charset = Encoding.WebName
oResponse.ContentType = "application/ms-excel"

' If you want the option to open the Excel file without saving than
' comment out the line below
' oResponse.Cache.SetCacheability(HttpCacheability.NoCache)

oStringWriter = New System.IO.StringWriter()
oHtmlWriter = New System.Web.UI.HtmlTextWriter(oStringWriter)
bAllowPaging = Me.AllowPaging
If bAllowPaging Then
Me.AllowPaging = False
If Me.RequiresDataBinding Then
Me.DataBind()
End If
End If

Me.RenderControl(oHtmlWriter)

If bAllowPaging Then
AllowPaging = bAllowPaging
End If
oResponse.Write(oStringWriter.ToString())
oResponse.End()
End Sub

End Class
End Namespace

沒有留言:

張貼留言