p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   ASP.NET 2.0 Basics (http://p2p.wrox.com/forumdisplay.php?f=136)
-   -   Problem in exporting data in a gridview to MSExcel (http://p2p.wrox.com/showthread.php?t=37722)

Rashmi_Dubey January 28th, 2006 06:58 AM

Problem in exporting data in a gridview to MSExcel
 
Hi,

I am trying to export data from a GridView to a Microsoft Excel file.

But, I got an error message as below:
"Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server" , though the control tag is already inside the form tag with runat=server.

Please advise.

Thanks & Regards,
Rashmi

Imar January 28th, 2006 07:36 AM

Hi Rashmi,

Can you show us the code for the page and/or Code Behind? Without code, it's hard to see what's going on...


Imar
---------------------------------------
Imar Spaanjaars
Everyone is unique, except for me.

Rashmi_Dubey January 28th, 2006 07:58 AM

Hi Imar,

I used the following code:

Response.AddHeader("contentdisposition","attachmen t;filename=test1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWrite(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();


But RenderControl doen't seem to work with GridView.

Thanks,
Rashmi

Imar January 28th, 2006 08:06 AM

Hi Rashmi,

Is GridView a control on your page? If so, this won't work. What you need to do is create an entirely new GridView control on the fly, databind it and then render it. E.g. (untested):
Code:

Response.AddHeader("contentdisposition","attachment;filename=test1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWrite(stringWrite);
GridView GridView1 = new GridView();
GridView1.DataSource = BusinessLayer.GetDataForControl();
GridView1.DataBind();

GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

This assumes that you let the GridView determine the columns (e.g. AutoGenerateColumns is true). If you need more control, you can add columns / templates/ styles to your GridView programmatically. Let me know if you need more information on that and I'll try to dig up an example.

Clearly, I just made up the BusinessLayer.GetDataForControl() method but I hope you get the idea....

mtscreator March 28th, 2006 04:49 PM

Hi,
This error can happen if you have paging or sorting turned on. What you do before exporting the datagrid to excel is to turn off paging and sorting, export your data, then turn your paging and sorting back on.


birch9397 April 26th, 2006 12:49 PM

Quote:

quote:Originally posted by mtscreator
 Hi,
This error can happen if you have paging or sorting turned on. What you do before exporting the datagrid to excel is to turn off paging and sorting, export your data, then turn your paging and sorting back on.



zaghmout November 13th, 2006 08:50 AM

guys i generated the gridview dynamically, but what happened is that the outcome was an empty excel sheet,
any suggestions?



robgerwing February 1st, 2007 01:42 PM

Here is the technique I use that have worked with me. I use master page as well. So hope this helps. You will see I added couple other things. This is base on ASP.NET 2.0 page. This is obviously a combination of different source on the internet and Imar's suggestion above creating new control.

1) On your ASPX add to Page Directive EnableEventValidation="false" Only use if the page complains about RenderControl must be in Form tag.

2) On the code behind of ASPX page as the following constructor:

public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
    }
3) On the code behind of your grid (either aspx or if load on user control put there) This works if Session is not controled in SQL DB.

//First Step
//Declare Grid control after public partial class

public GridView GridView1 = new GridView();


//Second Step Method for button onclick

protected void btnExport_Click(object sender, EventArgs e) {
        Response.Clear();

        Response.AddHeader("content-disposition", "attachment; filename=FileName_"+DateTime.Now.ToShortDateString ().Replace("/","_")+".xls");

        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.No Cache);
        Response.ContentType = "application/vnd.ms-xls";
        //"application/vnd.ms-excel"
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        //Reference the originally renders grid id name and your data source
        Session["ExportGridviewColumns"] = this.gvList.Columns;
        Session["ExportGridViewDataSource"] = this.objDsList.Select();

        //Add the columns to the print gridview
        foreach (DataControlField dcf in (DataControlFieldCollection)Session["ExportGridviewColumns"])
        {
            this.GridView1.Columns.Add(dcf);
        }

        //Turning off paging will avoid errors and get all contents
        //Provide some basic attributes to make excel data pretty

        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        GridView1.Font.Name = "Verdana";
        GridView1.Font.Size = 8;

        //Using ObjectDataSource Grabs Entire Contents
        this.GridView1.DataSource = Session["ExportGridViewDataSource"];
        this.GridView1.DataBind();

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End(); }

robgerwing February 1st, 2007 01:47 PM

Thanks Imar for the suggestion. Helped me out.

http://www.advernets.com

zaghmout March 11th, 2007 09:06 AM

Quote:

quote:Originally posted by robgerwing
 Here is the technique I use that have worked with me. I use master page as well. So hope this helps. You will see I added couple other things. This is base on ASP.NET 2.0 page. This is obviously a combination of different source on the internet and Imar's suggestion above creating new control.

1) On your ASPX add to Page Directive EnableEventValidation="false" Only use if the page complains about RenderControl must be in Form tag.

2) On the code behind of ASPX page as the following constructor:

public override void VerifyRenderingInServerForm(Control control)
    {
        // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
    }
3) On the code behind of your grid (either aspx or if load on user control put there) This works if Session is not controled in SQL DB.

//First Step
//Declare Grid control after public partial class

public GridView GridView1 = new GridView();


//Second Step Method for button onclick

protected void btnExport_Click(object sender, EventArgs e) {
        Response.Clear();

        Response.AddHeader("content-disposition", "attachment; filename=FileName_"+DateTime.Now.ToShortDateString ().Replace("/","_")+".xls");

        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.No Cache);
        Response.ContentType = "application/vnd.ms-xls";
        //"application/vnd.ms-excel"
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        //Reference the originally renders grid id name and your data source
        Session["ExportGridviewColumns"] = this.gvList.Columns;
        Session["ExportGridViewDataSource"] = this.objDsList.Select();

        //Add the columns to the print gridview
        foreach (DataControlField dcf in (DataControlFieldCollection)Session["ExportGridviewColumns"])
        {
            this.GridView1.Columns.Add(dcf);
        }

        //Turning off paging will avoid errors and get all contents
        //Provide some basic attributes to make excel data pretty

        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        GridView1.Font.Name = "Verdana";
        GridView1.Font.Size = 8;

        //Using ObjectDataSource Grabs Entire Contents
        this.GridView1.DataSource = Session["ExportGridViewDataSource"];
        this.GridView1.DataBind();

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End(); }


I tried this code and it worked perfectly, so thanks. but does anyone knows how I can export a report created in crystal report to MS_Word? I've done it in .pdf files, I managed to export the data into an excel sheet, I only need it as a word document :) so any suggestions?



All times are GMT -4. The time now is 08:57 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.