Pages

Subscribe:

Ads 468x60px

Saturday, October 13, 2012

import to excel in asp.net using c#

In this web programming tutorial we will learn that how we can import our Gridview data into excel file by click on a link button from our webpage in asp.net using c#.
  protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");        
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);     
        this.ClearControls(GridView1);
        GridView1.RenderControl(htw);       
        Response.Write(sw.ToString());
        Response.End();
    }
  private void ClearControls(Control ctrl)
    {
        for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(ctrl.Controls[i]);
        }

        if (!(ctrl is TableCell))
        {
            if (ctrl.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                ctrl.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
                }
                catch
                {

                }

                ctrl.Parent.Controls.Remove(ctrl);
            }

            else

                if (ctrl.GetType().GetProperty("Text") != null)
                {
                    if (ctrl.Visible == true)
                    {
                        LiteralControl literal = new LiteralControl();
                        ctrl.Parent.Controls.Add(literal);
                        literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
                        ctrl.Parent.Controls.Remove(ctrl);
                    }
                }
        }
        return;

    }

No comments:

Post a Comment