Wijmo GridView 控件不提供導出Excel文件的方法。本篇博客介紹一種將Wijmo的GridView控件保存到Excel的簡單方法。你可以使用同樣的方法在C1 WebUI GridView上。
步驟1 : 將C1GridView綁定至數據源
第一步是將C1GridView綁定到數據源。爲了簡單起見,我們將其綁定到C1Nwind.mdb的Customers表。
步驟2 : 導出C1GridView 至Excel
導出到Excel需要分成兩步。第一步是將GridView保存至一個HTML字符串。
Web控件有一個RenderControl()方法可以將服務器端控件的內容輸出到指定的HtmlTextWriter對象。如果啓用了Tracing,該方法還將存儲控件的Trace信息。然後該HtmlTextWriter對象輸出到一個StringWriter 對象。
下面的方法被用來創建一個字符串:
- Public Function DataGridToExcel(ByVal dgExport As C1.Web.Wijmo.Controls.C1GridView.C1GridView) As String
- '創建一個stringwriter
- Dim stringWrite As New System.IO.StringWriter()
- '創建一個使用該stringwriter的htmltextwriter
- Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
- Dim dg As C1.Web.Wijmo.Controls.C1GridView.C1GridView
- 'just set the input datagrid = to the new dg grid
- dg = dgExport
- '將header的字體加粗
- dg.HeaderStyle.Font.Bold = True
- '如果需要,這裏是在組件級別改變顏色/格式
- dg.HeaderStyle.ForeColor = System.Drawing.Color.Black
- dg.RowStyle.ForeColor = System.Drawing.Color.Black
- '綁定修改後的datagrid
- '告訴datagrid將自己呈現到我們提供的htmltextwriter
- dg.AllowSorting = False
- dg.AllowPaging = False
- dg.AllowCustomPaging = False
- '新的代碼
- Dim parent As Control = dg.Parent
- parent.Controls.Remove(dg)
- dg.RenderControl(htmlWrite)
- '新的代碼
- parent.Controls.Add(dg)
- '輸出HTML
- Return stringWrite.ToString()
- End Function
下一步,我們將在一個Button Click事件中調用這個DownloadToExcel 方法從保存的字符串創建一個excel文件。
- Public Sub DownloadToExcel(ByVal content As String, ByVal response As HttpResponse)
- '清理 response.object
- response.Clear()
- response.Buffer = True
- response.Charset = ""
- '設置響應的MIME類型爲excel
- response.ContentType = "application/vnd.ms-excel"
- response.ContentEncoding = New System.Text.UTF8Encoding()
- response.Write(content)
- response.End()
- End Sub
實現時的問題
在相當多的情況下,你會在導出時遇到一些錯誤。你可能會收到一條錯誤信息:“RegisterForEventValidation 只能在Render()過程中被調用;”。在這種情況下,請嘗試以下方法:
1. 你可以向下面的文章描述的那樣,重載VerifyRenderingInServerForm 方法:
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
End Sub
2. 爲了避免收到“RegisterForEventValidation 只能在Render()過程中被調用;”異常,可以關閉Page.EnableEventValidation 或者將RenderControl方法調用放置在一個try-catch塊中。
此外,如果gridview包含一個複選框或者一個模板列,你會收到上面的錯誤。目前已發現微軟發佈的GridView會發生同樣的錯誤。由於C1GridView繼承自微軟發佈的GridView,所以它是C1GridView的已知設計問題。
Wijmo下載,請進入Studio for ASP.NET Wijmo 2012 v1正式發佈(2012.03.22更新)!