I have a need to export the contents in a ComponentArt Grid into a file, preferably excel in csv format.
I was wondering if anyone had any ideas how to best approach this task. At the moment we have the grid being populated with data, and using client templating some minor manipulation is being performed before it is displayed to the user.
An example of a template that is applied is:
<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" />
So when the grid is exported I would like the file to contain what is in the grid at the moment of export including any templated changes that may be visible if possible.
Thank you in advance for your assistance.
You cannot export the Web.UI Grid directly using RenderControl into a text writer. Instead, you should convert its data into another form (such as the ASP DataGrid) and export that instead.
The reason behind this is that the Web.UI Grid's structure is build dynamically on the client -- it's passed from server to client as a bunch of XML and array data, which is converted into the tables and divs that you see in the window.
As a result you'll want to perform the export on the Grid's datasource, and then analyze the client templates to replicate what they would change when built dynamically on the client.
The following is a short example of how to export the CA grid it into 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();
}
So before binding the datasource of the GridView you will want to perform the ClientTemplate replication.