Export Gridview/Listview to Excel with Color formatting


Introduction:

Here in this article I explain on how to export Gridview / Listview to excel with same color formatting using .net. Based on the gridivew fomatting we have to export with same row alignment and format.

Export to Excel:

It's shows that using .net we are export gridvie to excel with color formatting that we are initialized in the girdview. It explains that we extract same thing what we have in the gridview.

Initially generate the temp data to bind into the datagrid.

//Create temp datatable for bind values
DataTable dtTemp = new DataTable(); DataRow dr;
//create schema
dtTemp.Columns.Add("CustId"); dtTemp.Columns.Add("CusName");
//Add temp datas
dr = dtTemp.NewRow(); dr["CustId"] = "1"; dr["CusName"] = "AA1"; dtTemp.Rows.Add(dr);
dr = dtTemp.NewRow(); dr["CustId"] = "2"; dr["CusName"] = "BB2"; dtTemp.Rows.Add(dr);
dr = dtTemp.NewRow(); dr["CustId"] = "3"; dr["CusName"] = "CC3"; dtTemp.Rows.Add(dr);
dr = dtTemp.NewRow(); dr["CustId"] = "4"; dr["CusName"] = "DD4"; dtTemp.Rows.Add(dr);
dr = dtTemp.NewRow(); dr["CustId"] = "5"; dr["CusName"] = "EE5"; dtTemp.Rows.Add(dr);

Once get the data, just proceed the below code and export into the excel. You can alter the cells and header based on the requirements and UI.

//Reponse content
Response.AddHeader("content-disposition", "attachment; filename=ExportExcel.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
//Objects
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//Add the control to the forms
DataGrid dgRecord= new DataGrid();
this.form1.Controls.Add(dgRecord);
//Color Setttings
dgRecord.HeaderStyle.BackColor = System.Drawing.Color.Blue;
dgRecord.DataSource = dtTemp;
dgRecord.DataBind();
//Cells color settings
foreach (DataGridItem dgi in dgRecord.Items)
    foreach (TableCell tcGridCells in dgi.Cells)
        tcGridCells.Attributes.Add("class", "sborder");
//Render the datagrid
dgRecord.RenderControl(htmlWrite);
//Add the style sheet class here
Response.Write(@"<style> .sborder { color : Red;border : 1px Solid Balck; } </style> ");
//Export
Response.Write(stringWrite.ToString());
//End
Response.End();