Write data to Excel file (.xls and .xlsx) with Master Pages in ASP.Net

Last Reply on Sep 23, 2015 07:32 AM By Shashikant

Posted on Sep 22, 2015 11:17 AM

 

hi Mudassar Sir, 

I am learning Asp.net programming.  I was very much fond of Your Help in this forum.

Sir,  I have following  problem:

I am referring to your example in below url:

http://www.aspsnippets.com/Articles/Write-data-to-Excel-file-xls-and-xlsx-in-ASPNet.aspx

the code works good when my webform is not inside content place holder of Master page.

but, when i use same code in the webform which lies inside content place holder of a Master page, 
downloading of excel doesnot happen.

I dont know why. Sir kindly Help....

 

 

 

 

 

Posted on Sep 23, 2015 07:32 AM

Here I have created sample using Master page and Content Page

Default.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <asp:Button ID="Button2" Text="Export" OnClick="ExportExcel" runat="server" />
</asp:Content>

Code

protected void ExportExcel(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    using (XLWorkbook wb = new XLWorkbook())
                    {
                        wb.Worksheets.Add(dt, "Customers");

                        Response.Clear();
                        Response.Buffer = true;
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
                        using (MemoryStream MyMemoryStream = new MemoryStream())
                        {
                            wb.SaveAs(MyMemoryStream);
                            MyMemoryStream.WriteTo(Response.OutputStream);
                            Response.Flush();
                            Response.End();
                        }
                    }
                }
            }
        }
    }
}

MasterPage

<div>
    <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
    </asp:contentplaceholder>
</div>

Screenshot