rakesh chaudhari

rakesh chaudhari

  • NA
  • 115
  • 35.6k

export to excel

Apr 30 2014 6:04 AM

How to Export GridView to Excel (xlsx, Excel 2007,10 Format) ?

my code is as 
public void ExportDataExcel(DataTable dt)
{
Response.Clear();
Response.ClearContent();
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.AddHeader("Content-Disposition", "attachment;filename=" + "OpenComplaints" + ".xlsx");

using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{

htw.RenderBeginTag(HtmlTextWriterTag.Link);
htw.RenderEndTag();

// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.GridLines = GridLines.Both;
dg.CaptionAlign = TableCaptionAlign.Left;
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.ForeColor = System.Drawing.Color.DarkBlue;
dg.HeaderStyle.BackColor = System.Drawing.Color.SkyBlue;
dg.ItemStyle.BackColor = System.Drawing.Color.LightGray;
dg.ItemStyle.Width = 100;
dg.ItemStyle.Wrap = true;
dg.DataSource = dt;
dg.DataBind();

dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
}
}






Please help me  when i call this function then it give only blank excel sheet without any column or row or header so plz help and thanks in advance

Answers (6)