ComponentArt:导出网格数据

我需要将ComponentArt网格中的内容导出到文件中,最好以csv格式表示。

我想知道如果有人有任何想法如何最好地处理这个任务。 目前,我们已经在网格中填充数据,并且在向用户显示之前使用客户端模板进行一些小的操作。

应用的模板的一个例子是:

<ComponentArt:ClientTemplate Id="PostTemplate"> ## DataItem.GetMember("LastPostBy").Value ##<br />## DataItem.GetMember("LastPostDate").Value ## </ComponentArt:ClientTemplate> Where the column definitions are: <ComponentArt:GridColumn Width="140" HeadingText="Last Post By " DataCellClientTemplateId="PostTemplate" /> <ComponentArt:GridColumn DataField="LastPostBy" Visible="false" /> <ComponentArt:GridColumn DataField="LastPostDate" Visible="false" /> 

所以当网格导出时,我希望文件包含导出时的网格内容,如果可能的话包括任何模板更改。

预先感谢您的帮助。

您不能直接使用RenderControl将Web.UI网格导出到文本编写器中。 相反,您应该将其数据转换为另一种forms(如ASP DataGrid)并导出。

其原因是Web.UI网格的结构是在客户端上dynamic构build的 – 它从服务器传递到客户端,形成一堆XML和数组数据,并将其转换为您在窗口中看到的表格和div。

因此,您需要在Grid的数据源上执行导出,然后分析客户端模板以复制在客户端上dynamic生成时要更改的内容。

以下是如何将CA网格导出到excel的简短示例:

 public void ExportDataSetToExcel() { object theColl = gridEmployee.DataSource; //just set this as your grid's datasource. GridView excelGrid = new GridView(); excelGrid.DataSource = theColl; excelGrid.ID = "Export"; excelGrid.DataBind(); excelGrid.AutoGenerateColumns = true; Response.Clear(); Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment;filename=RegainExport.xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); excelGrid.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } 

因此,在绑定GridView的数据源之前,您需要执行ClientTemplate复制。

我要做的是我将在用户控件.ascx文件中定义组件艺术控件(以及模板)。 然后,您可以使用这个小代码片段将此控件呈现为一个string:

 StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) using (HtmlTextWriter textWriter = new HtmlTextWriter(sw)) { theGrid.RenderControl(textWriter); } string gridContent = sb.ToString(); 

现在,你有HTML格式的网格内容。 从那里,假设组件艺术已经形成良好的标记,你可以考虑将XMLparsing为XML,并拉出单元格值变成你的CSV。

假设你想允许用户通过浏览器保存CSV文件,你可以实现一个自定义的http处理程序来呈现控件,创buildCSV文件,然后以“text / csv”的forms发送给浏览器。