Wijmo 更优美的jQuery UI部件集:导出Wijmo的GridView到Excel

Wijmo GridView 控件不提供导出Excel文件的方法。本篇博客介绍一种将Wijmo的GridView控件保存到Excel的简单方法。你可以使用同样的方法在C1 WebUI GridView上。

 

步骤1 : C1GridView绑定至数据源

第一步是将C1GridView绑定到数据源。为了简单起见,我们将其绑定到C1Nwind.mdb的Customers表。

image

 

步骤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
复制代码

 

 

image

 

下一步,我们将在一个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
复制代码

 

 image

 

实现时的问题

在相当多的情况下,你会在导出时遇到一些错误。你可能会收到一条错误信息:“RegisterForEventValidation 只能在Render()过程中被调用;”。在这种情况下,请尝试以下方法:


1. 你可以向下面的文章描述的那样,重载VerifyRenderingInServerForm 方法:

http://connect.microsoft.com/VisualStudio/feedback/details/118285/rendercontrol-doesnt-work-for-gridview

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更新)!

posted @   葡萄城技术团队  阅读(3466)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示