Click here to Skip to main content
15,913,587 members
Please Sign up or sign in to vote.
4.60/5 (3 votes)
See more:
I use this code for exporting data to excel from gridview ..
C#
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True"
                               OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
                               OnRowCancelingEdit="GridView1_RowCancelingEdit">
                               <columns>
                                   <asp:TemplateField HeaderText="Product Name">
                                       <itemtemplate>
                                           <asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'>
                                       </itemtemplate>

                                   <asp:TemplateField HeaderText="Qty">
                                       <itemtemplate>
                                           <asp:Label ID="lblQty" runat="server" Text='<%# Eval("Qty") %>'>
                                       </itemtemplate>
                                       <edititemtemplate>
                                           <asp:TextBox ID="txtQty" runat="server" Text='<%# Eval("Qty") %>' Width="50px">
                                       </edititemtemplate>

                                   <asp:TemplateField HeaderText="Price">
                                       <itemtemplate>
                                           <asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price") %>'>
                                       </itemtemplate>

                                   <asp:TemplateField HeaderText="Total Price">
                                       <itemtemplate>
                                           <asp:Label ID="lblTotalPrice" runat="server" Text='<%# Eval("Total") %>'>
                                       </itemtemplate>

                                   <asp:TemplateField HeaderText="Edit">
                                       <edititemtemplate>
                                           <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update"
                                               CommandArgument='<%# Eval("ProductID") %>'>
                                           <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                               CommandArgument='<%# Eval("ProductID") %>'>
                                       </edititemtemplate>
                                       <itemtemplate>
                                           <asp:LinkButton ID="lblEditItem" runat="server" Text="Edit" CommandName="Edit" CommandArgument='<%# Eval("ProductID") %>' />
                                       </itemtemplate>

                                   <asp:TemplateField HeaderText="Cancel">
                                       <itemtemplate>
                                           <asp:LinkButton ID="lblCancelItem" runat="server" Text="Cancel" CommandArgument='<%# Eval("ProductID") %>'
                                               OnClick="lblCancelItem_Click" />
                                       </itemtemplate>

                               </columns>



C#
protected void BindData()
        {
            DataTable result = (DataTable)Session["MyTable"];
            if (result.Rows.Count > 0)
            {
                GridView1.DataSource = result;                
                GridView1.DataBind();
            }
        }




C#
protected void Export2Excel()
        {
            try
            {
                this.GridView1.AllowPaging = false;
                this.GridView1.AllowSorting = false;
                this.GridView1.EditIndex = -1;

                // Let's bind data to GridView
                this.BindData();

                // Let's output HTML of GridView
                Response.Clear();
                Response.ContentType = "application/vnd.xls";
                Response.AddHeader("content-disposition",
                        "attachment;filename=MyList.xls");
                Response.Charset = "";
                StringWriter swriter = new StringWriter();
                HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
                GridView1.RenderControl(hwriter);
                Response.Write(swriter.ToString());
                Response.End();
            }
            catch (Exception exe)
            {
                throw exe;
            }
         
        }       



But when i execute this method at that time i got this error

C#
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.


i got this code from web.
Where i am wrong....
Posted
Updated 16-Sep-11 19:33pm
v3

Try this code

C#
private void ExportToExcel(string strFileName, GridView gv)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
        Response.ContentType = "application/excel";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        issueListGridView.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
 
Share this answer
 
v2
Just Put Ur Enyire <body></body> in a <Form runat="server"></form> tag then it ll works
 
Share this answer
 
In VB.Net

============================================================

VB
Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

      ' Verifies that the control is rendered
  End Sub



============================================================

Hope It works....

Regards,
Syed Abid Ali Abdi
 
Share this answer
 
Thanks for all of you to give me solutions...

Now i got my mistake and i solve it now it work perfectly..

i have added a update panel so i got that error when i remove my update panel the same code work without error..
 
Share this answer
 
v2
 
Share this answer
 
Comments
raj ch 17-Sep-11 1:54am    
nice link Thiyagarajan.
rkthiyagarajan 17-Sep-11 20:40pm    
Thanks....
Tejas Vaishnav 17-Sep-11 2:26am    
Thanks
C#
 <form runat="SERVER">
   <gridview>
    ...
   </gridview>
 
</form>



follow this format to try again.
 
Share this answer
 
Comments
Tejas Vaishnav 17-Sep-11 2:24am    
Thanks
I ahve used this tool
Export to excel
It's very good
 
Share this answer
 
Comments
Tejas Vaishnav 17-Sep-11 2:24am    
Thanks
With help of this class u can export grid view data in Excel.Only pass 2 parameter file name and grid instance.


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

using iTextSharp.text;
using iTextSharp.text.pdf;






/// <summary>
/// Summary description for ExcelExport
/// </summary>
public class ExcelExport
{

public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment;filename={0}", fileName));
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();

// include the gridline settings
table.GridLines = gv.GridLines;

// add the header row to the table
if (gv.HeaderRow != null)
{
ExcelExport.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}

// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ExcelExport.PrepareControlForExport(row);
table.Rows.Add(row);
}

// add the footer row to the table
if (gv.FooterRow != null)
{
ExcelExport.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

// 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();
}
}
}

/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(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 ? "True" : "False"));
}

if (current.HasControls())
{
ExcelExport.PrepareControlForExport(current);
}
}
}


}
 
Share this answer
 
Comments
Tejas Vaishnav 17-Sep-11 2:24am    
Thanks
It sounds like your design view isn't formatted correclty - open the design view and find your GridView1 control and check the syntax
 
Share this answer
 
Comments
Tejas Vaishnav 17-Sep-11 1:32am    
I have added my gridview code also please tell me where i m wrong...

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