Click here to Skip to main content
15,890,370 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

I have a gridview and 3 charts on my asp page which I want to export to excel and able to do that. However, I am not able to export the gridview on sheet 1 and charts on sheet2 in excel.

Please help me...

Below is my code:

What I have tried:

C#
protected void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {    
            string imgName1 = Session["tmpChartName1"].ToString();
            string imgName2 = Session["tmpChartName2"].ToString();
            string imgName3 = Session["tmpChartName3"].ToString();
            string imgPath1 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + imgName1);
            string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + imgName2);
            string imgPath3 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + imgName3);

            Response.Clear();
            Response.Buffer = true;
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Charset = "";
            string filename="";

            filename = "GridData_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx"
            
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

            GridView gv = new GridView();
            gv.DataSource = dt;
            gv.DataBind();

            gv.GridLines = GridLines.Both;
            gv.HeaderStyle.Font.Bold = true;
            gv.RenderControl(hw);
            string headerTable1 = @"";
            string headerTable2 = @"";
            string headerTable3 = @"";
            Response.Write(headerTable1);
            Response.Write(headerTable2);
            Response.Write(headerTable3);
            Response.Write(sw.ToString());
            Response.End();           
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('Data not available!')", true);
        }
    }
Posted
Updated 30-Mar-18 21:23pm
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900