Export Gridview/Listview to Excel with Color Formatting

Introduction

In this article, I explain how to export Gridview / Listview to Excel with the same color formatting using .NET. Based on the grid view formatting, we have to export with the same row alignment and format.

Export to Excel

It shows that using .NET, we export the grid view to Excel with color formatting that we are initialized in the girdview. It explains that we extract the same thing that we have in the grid view.

Initially, the temp data is generated to bind to the data grid.

// Create temp DataTable for bind values
DataTable dtTemp = new DataTable();
DataRow dr;

// Create schema
dtTemp.Columns.Add("CustId");
dtTemp.Columns.Add("CusName");

// Add temp data
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 you get the data, just proceed with the below code and export it into Excel. You can alter the cells and header based on the requirements and UI.

// Response content
Response.AddHeader("content-disposition", "attachment; filename=ExportExcel.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";

// 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 Settings
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 Black; } </style> ");

// Export
Response.Write(stringWrite.ToString());

// End
Response.End();


Similar Articles