Hi,
If you want to apply styles while export your datacontrol information into excel then refer below sample code to achieve your goal.
protected void Export(string fileName, GridView gv)
{
//HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
gv.HeaderRow.Style.Add("border", "solid 1px #336633");
table.Rows.Add(gv.HeaderRow);
TableRow tRow = gv.HeaderRow;
tRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "#336633";
tRow.Style[System.Web.UI.HtmlTextWriterStyle.Color] = "White";
}
// add each of the data rows to the table
for (int i = 0; i < gv.Rows.Count; i++)
{
GridViewRow row = gv.Rows[i];
PrepareControlForExport(row);
row.Style.Add("border", "solid 1px #336633");
row.BackColor =System.Drawing.Color.FromName("#EEFDB9");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#FFFFCC");
row.Cells[1].Style.Add("background-color", "#FFFFCC");
row.Cells[2].Style.Add("background-color", "#FFFFCC");
row.Cells[3].Style.Add("background-color", "#FFFFCC");
row.Cells[4].Style.Add("background-color", "#FFFFCC");
row.Cells[5].Style.Add("background-color", "#FFFFCC");
row.Cells[6].Style.Add("background-color", "#FFFFCC");
row.Cells[7].Style.Add("background-color", "#FFFFCC");
row.Cells[8].Style.Add("background-color", "#FFFFCC");
row.Cells[9].Style.Add("background-color", "#FFFFCC");
row.Cells[10].Style.Add("background-color", "#FFFFCC");
row.Cells[11].Style.Add("background-color", "#FFFFCC");
row.Cells[12].Style.Add("background-color", "#FFFFCC");
row.Cells[13].Style.Add("background-color", "#FFFFCC");
row.Cells[14].Style.Add("background-color", "#FFFFCC");
row.Cells[15].Style.Add("background-color", "#FFFFCC");
}
table.Rows.Add(row);
table.CssClass = "exampleDiv";
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
Prabhukiran345, if this helps please login to Mark As Answer. | Alert Moderator