Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

I have used the following code to export values in a grid to excel 2007.
I am getting the Gridview must be inside form tag error.
as far as i can see it is inside the form tag.
Am I missing something here?

C#
Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xlsx");
            Response.Charset = "";
            this.EnableViewState = false;

            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            grdExcel.RenderControl(htw);

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


XML
<head runat="server">
    <title>Excel Import Test</title>
</head>
<body>
    <form id="form1" runat="server">
       <table>
   <tr>
      <td> </td>
      <td><asp:Button ID="ButtonView" runat="server"
         Text="View Excel Data" OnClick="ButtonView_Click" /> </td>
      <td>  &nbsp;</td>
         <td>  <asp:Button ID="ButtonSave" runat="server"
         Text="Save Excel Data" OnClick="ButtonSave_Click" />  </td>
          <td>  <asp:Button ID="ButtonExport" runat="server"
         Text="Export to Excel" OnClick="ButtonExport_Click"  />  </td>
   </tr>
</table>

 <asp:GridView ID = "grdExcel" runat = "server" CellPadding="4" ForeColor="#333333" GridLines="None" >
     <RowStyle BackColor="#EFF3FB" />
     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
     <EditRowStyle BackColor="#2461BF" />
     <AlternatingRowStyle BackColor="White" />
 </asp:GridView>
  </form>


Thanks.
Posted
Updated 15-Sep-11 23:57pm
v2

With help of this class u can export grid view data in Excel.Only pass 2 parameter file name and grid instance.

C#
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
 
v2
You can use this tool
Export to Excel
 
Share this answer
 
Nice link to Export to EXCEL[^]
 
Share this answer
 

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