AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Wednesday, 2 March 2016

Export excel file on button click in asp.net.

In this article I will discuss how to export excel file in asp.net. On click download button excel file will download. Please check below code.


<asp:LinkButton ID="lnkGenerateReport" runat="server" ToolTip="Download Report" CssClass="btn btn-default btn-xs pull-right" OnClick="lnkGenerateReport_Click">  <i class="fa fa-download"></i></asp:LinkButton>

Add new report entity class
 public Class ReportDataEntity()
   {
     public string Name{get;set;}
     public int StandardOfferCount{get;set;}
     public int ProductOfferCount{get;set;}
   }

Generate Excel report code:
 #region--Generate Excel--
    protected void lnkGenerateReport_Click(object sender, EventArgs e)
    {        
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "ToDaysOfferAddedReport"+DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss") + ".xls"));
        Response.ContentType = "application/ms-excel";
        List<ReportDataEntity> Report = GetOfferData(); // Write your logic to fetch data
        string str = string.Empty;
        Response.Write(str + "Name");
        str = "\t";
        Response.Write(str + "Standard Offer Count");
        str = "\t";
        Response.Write(str + "Product Offer Count");
        str = "\t";
        Response.Write("\n");
        foreach (ReportDataEntity dr in Report)
        {
            str = "";            
            Response.Write(str + Convert.ToString(dr.MerchantName));
            str = "\t";
            Response.Write(str + Convert.ToString(dr.StandardOfferCount));
            str = "\t";
            Response.Write(str + Convert.ToString(dr.ProductOfferCount));
            str = "\t";
          
            Response.Write("\n");
        }
        Response.End();
    }
    #endregion

On click download report button browser will alert excel file.

0 comments :

Post a comment

  • Popular Posts
  • Comments