步骤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
复制代码
Studio for ASP.NET Wijmo 2012 v1正式发布(2012.03.22更新)!