Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Response.Write("Export to excel");
        Response.Clear();
        Response.Charset = "";
        
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-disposition", "attachment;filename=Demo.xls");
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter stringwriter = new StringWriter();
        HtmlTextWriter htmwrite = new HtmlTextWriter(stringwriter);
        GridView1.RenderControl(htmwrite);
        Response.Write(stringwriter.ToString());
        Response.End();

This  is my code to export gridview to excel. but an error is shown as
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Pls help me to correct this
Posted
Updated 24-Jul-16 23:48pm
v2
Comments
Al Moje 25-Oct-11 0:36am    
Hi,
I think the error is not in your code behind, because it's clear error message
'Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server'. Advise you review you 'Client code'. Or you may post your Client Code so that others may help you...
Satish Acharya 6-Jul-12 7:21am    
This error is also persist in my code also.I think its because There is multiple runat server attribute at page.Remove it

 
Share this answer
 
check your design code,
put gridview1 inside form tag or ContentPlaceholder with runat="Server"
You can use another tool to Export gridview to Excel with same Formate
Export to Excel
 
Share this answer
 
Add these Codes in your aspx page

C#
public override void RenderControl(HtmlTextWriter writer)
   {
       base.RenderControl(writer);
   }
   protected override void RenderChildren(HtmlTextWriter writer)
   {
       base.RenderChildren(writer);
   }
   public override void VerifyRenderingInServerForm(Control control)
   {
       //base.VerifyRenderingInServerForm(control);
   }


Regards
Sheik
 
Share this answer
 
 
Share this answer
 
Comments
Dalek Dave 25-Oct-11 3:42am    
Nice links.
First drag the gridview control on aspx page

then add button control

<asp:Button onclick="Button1_Click" text="Export to Excel" runat="server" id="Button1"/>


and on .cs page paste this code


protected void Button1_Click(object sender, EventArgs e)
    {
   
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "Exported"));
        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                 Table table = new Table();

                foreach (GridViewRow row in gvBankReco.Rows)
                {
                    VerifyRenderingInServerForm(row);
                    table.Rows.Add(row);
                   
                }
                
                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
        Control current = control.Controls[i];
        if (current is LinkButton)
        {
        control.Controls.Remove(current);
        control.Controls.AddAt(i, new LiteralControl((current as
        LinkButton).Text));
        }
        else if (current is ImageButton)
        {
        control.Controls.Remove(current);
        control.Controls.AddAt(i, new LiteralControl((current as
        ImageButton).AlternateText));
        }
        else if (current is HyperLink)
        {
        control.Controls.Remove(current);
        control.Controls.AddAt(i, new LiteralControl((current as
        HyperLink).Text));
        }
        else if (current is DropDownList)
        {
        control.Controls.Remove(current);
        control.Controls.AddAt(i, new LiteralControl((current as
        DropDownList).SelectedItem.Text));
        }
        else if (current is CheckBox)
        {
        control.Controls.Remove(current);
        control.Controls.AddAt(i, new LiteralControl((current as
        CheckBox).Checked ? "כן" : "לא"));
        }
        if (current.HasControls())
        {
           VerifyRenderingInServerForm(current);
        }
        }
        // Confirms that an HtmlForm control is rendered for the
        //specified ASP.NET server control at run time.
    }


I hope by doing this your problem will be solve.
 
Share this answer
 
Below Code in aspx page

  <asp:Button ID="lnkbtnExport" runat="server" Text="Export Report To Excel" style="background-color: #39424c; border-color: #000; color: #ffffff;  border-radius: 15px; height: 28px;
width: 180px;"></asp:Button>


ASP.NET
<div style="display:none;">
    	    <asp:GridView ID="GridView1" HeaderStyle-BackColor="White" HeaderStyle-ForeColor="Black" HeaderStyle-CssClass="fa-border" 
        RowStyle-BackColor="Gray" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
        runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
        <Columns>
            <asp:BoundField DataField="Cdate" HeaderText="Create Date" ItemStyle-Width="100px" DataFormatString="{0:dd/MM/yyyy hh:mm tt}" />
            <asp:BoundField DataField="Name" HeaderText="Contact Name" ItemStyle-Width="150px" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile" ItemStyle-Width="100px" />
            <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
            <asp:BoundField DataField="Company" HeaderText="Company" ItemStyle-Width="100px" />
            <asp:BoundField DataField="Email" HeaderText="Email Address" ItemStyle-Width="100px" />
            <asp:BoundField DataField="DeviceType" HeaderText="Device Type" ItemStyle-Width="100px" />
            <asp:BoundField DataField="IpAddress" HeaderText="Ip Address" ItemStyle-Width="100px" />
            <asp:BoundField DataField="Mac" HeaderText="Mac Address" ItemStyle-Width="100px" />
        </Columns>
    </asp:GridView>
        </div>


below code in aspx.cs page

C#
protected void lnkbtnExport_Click(object sender, EventArgs e)
{
	Response.Clear();
	Response.Buffer = true;
	Response.AddHeader("content-disposition", "attachment;filename=ClientList.xls");
	Response.Charset = "";
	Response.ContentType = "application/vnd.ms-excel";
	using (StringWriter sw = new StringWriter()) {
		HtmlTextWriter hw = new HtmlTextWriter(sw);

		//To Export all pages
		GridView1.AllowPaging = false;
		this.BindGrid();


		if (GridView1.Rows.Count > 0) {
			GridView1.HeaderRow.BackColor = Color.White;
			foreach (TableCell cell in GridView1.HeaderRow.Cells) {
				cell.BackColor = GridView1.HeaderStyle.BackColor;
			}
			foreach (GridViewRow row in GridView1.Rows) {
				row.BackColor = Color.White;
				foreach (TableCell cell in row.Cells) {
					if (row.RowIndex % 2 == 0) {
						//cell.BackColor = GridView1.AlternatingRowStyle.BackColor
					} else {
						//cell.BackColor = GridView1.RowStyle.BackColor
					}
					cell.CssClass = "textmode";
				}
			}

			GridView1.RenderControl(hw);
			//style to format numbers to string
			string style = "<style> .textmode { mso-number-format:\\@; } </style>";
			Response.Write(style);
		}

		Response.Output.Write(sw.ToString());
		Response.Flush();
		Response.End();


	}
}
 
Share this answer
 
v2

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