Asp. NET Export data to Excel implementation method

Source: Internet
Author: User
Tags httpcontext print format stack trace
When the ASP.net program involves data display when most will require printing, and the page on the print format is often not meet the needs of the often used method is to import into Excel and then print.   (as if this is already a cliché) today on the Internet to search a piece of printed code, feel good, need to print friends can see.

Some of the code on the web is basically similar to the principle, there is also a problem, is:
The control "Ctl00_center_gridview1" of type "GridView" must be placed inside a form tag that has a runat=server. Note: An unhandled exception occurred during the execution of the current WEB request. Check the stack trace for more information about the error and where the error occurred in the code. Exception Details: System.Web.HttpException: The control "ctl00_center_gridview1" of the type "GridView" must be placed inside a form tag with Runat=server.
The error description is that I'm commenting that this procedure is a false quote,

Copy Code code as follows:


//publicoverridevoidverifyrenderinginserverform (Controlcontrol)


//{


////base. Verifyrenderinginserverform (Control);


//}


Although the contents of this method are also commented, that is, this is an empty method, but if there is no method, the program will report the above error. The first time you see this error is to think of a previous error in Ajax program times is very similar. The same is the result of not rewriting the Verifyrenderinginserverform method. In this reminder to use the friend note, the following posted code exported to Excel

Copy Code code as follows:




Usingsystem;


Usingsystem.data;


usingsystem.configuration;


Usingsystem.collections;


Usingsystem.web;


usingSystem.Web.Security;


UsingSystem.Web.UI;


UsingSystem.Web.UI.WebControls;


UsingSystem.Web.UI.WebControls.WebParts;


UsingSystem.Web.UI.HtmlControls;


Usingsystem.io;


///<summary>


///toexclehelper's summary description


///</summary>


Publicclassexporthelper


{


Publicstaticvoidexporttoexcel (ilistdatalist,string[]fields,string[]headtexts,stringtitle)


{


Gridviewgvw=newgridview ();


Intcolcount,i;


///If the filtered field and the corresponding column header name number are relative, only the specified fields are exported


if (fields. Length!=0&&fields. Length==headtexts.length)


{


Colcount=fields. Length;


GVW. Autogeneratecolumns=false;


for (i=0;i<colcount;i++)


{


Boundfieldbf=newboundfield ();


BF. Datafield=fields[i];


BF. Headertext=headtexts[i];


GVW. Columns.Add (BF);


}


}


Else


{


GVW. Autogeneratecolumns=true;


}


Setstype (GVW);


GVW. Datasource=datalist;


GVW. DataBind ();


exportToExcel (Gvw,title);


}


///<summary>


///Export data to Excel


///</summary>


///<paramname= "DataList" >IListData</param>


///<paramname= "Fields" > Fields to export </param>


///<paramname= "headname" > field corresponds to the display name </param>


Publicstaticvoidexporttoexcel (ilistdatalist,string[]fields,string[]headtexts)


{


exportToExcel (datalist,fields,headtexts,string. Empty);


}


///<summary>


///Set Style


///</summary>


///<paramname= "GVW" ></param>


Privatestaticvoidsetstype (GRIDVIEWGVW)


{


GVW. Font.name= "Verdana";


GVW. Borderstyle=system.web.ui.webcontrols.borderstyle.solid;


GVW. Headerstyle.backcolor=system.drawing.color.lightcyan;


GVW. Headerstyle.forecolor=system.drawing.color.black;


GVW. Headerstyle.horizontalalign=system.web.ui.webcontrols.horizontalalign.center;


GVW. Headerstyle.wrap=false;


GVW. Headerstyle.font.bold=true;


GVW. headerstyle.font.size=10;


GVW. rowstyle.font.size=10;


}


///<summary>


///Export the data in the GridView to Excel


///</summary>


///<paramname= "GVW" ></param>


///<paramname= "DataList" ></param>


Publicstaticvoidexporttoexcel (Gridviewgvw,stringtitle)


{


Stringfilename;


httpcontext.current.response.buffer=true;


HttpContext.Current.Response.ClearContent ();


HttpContext.Current.Response.ClearHeaders ();


filename=string. Format ("Xhmd{0:yymmddhhmm}.xls", DateTime.Now);


HttpContext.Current.Response.AppendHeader ("Content-disposition", "attachment;filename=" +filename);


httpcontext.current.response.contenttype= "application/vnd.ms-excel";


Stringwritertw=newsystem.io.stringwriter ();


htmltextwriterhw=newsystem.web.ui.htmltextwriter (TW);


GVW. RenderControl (HW);


if (!string. IsNullOrEmpty (title))


{


HttpContext.Current.Response.Write ("<b><center><fontsize=3face=verdanacolor= #0000FF >" + Title+ "</font></center></b>");


}


HttpContext.Current.Response.Write (TW. ToString ());


HttpContext.Current.Response.Flush ();


HttpContext.Current.Response.Close ();


HttpContext.Current.Response.End ();


GVW. Dispose ();


tw. Dispose ();


HW. Dispose ();


Gvw=null;


Tw=null;


Hw=null;


}


Publicstaticvoiddatatable2excel (System.Data.DataTabledtData)


{


System.web.ui.webcontrols.datagriddgexport=null;


//Current dialog


system.web.httpcontextcurcontext=system.web.httpcontext.current;


//io is used to export and return an Excel file


System.io.stringwriterstrwriter=null;


System.web.ui.htmltextwriterhtmlwriter=null;


if (dtdata!=null)


{


//Set encoding and attachment format


curcontext.response.contenttype= "application/vnd.ms-excel";


Curcontext.response.contentencoding=system.text.encoding.utf8;


curcontext.response.charset= "";





//Export Excel file


Strwriter=newsystem.io.stringwriter ();


Htmlwriter=newsystem.web.ui.htmltextwriter (Strwriter);


//To resolve a possible paging situation in the dgdata, you need to redefine a DataGrid that has no paging


Dgexport=newsystem.web.ui.webcontrols.datagrid ();


Dgexport.datasource=dtdata.defaultview;


Dgexport.allowpaging=false;


Dgexport.databind ();


//Back to client


Dgexport.rendercontrol (HTMLWriter);


CurContext.Response.Write (strwriter.tostring ());


curContext.Response.End ();


}


}


}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.