ASP. NET export Excel (HTML output method)

Source: Internet
Author: User
Tags httpcontext

Main ideas:

Instantiate gridview, bind value after output ... (In a rotten way)

Paste the core code:
  Public Static voidexportToExcel (DataTable dataList,string[] fields,string[] headtexts,stringTitlestringTableName) {GridView GVW=NewGridView (); intColCount, I; //If the filter field and the corresponding column header name 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++) {BoundField bf=NewBoundField (); Bf. DataField=Fields[i]; Bf. HeaderText=Headtexts[i]; Gvw.            Columns.Add (BF); }        }        Else{GVW. AutoGenerateColumns=true; } GVW. DataSource=dataList;        Setstype (GVW); Gvw.        DataBind ();    exportToExcel (GVW, title, TableName); }    /// <summary>    ///Export data to Excel/// </summary>    /// <param name= "DataList" >IList Data</param>    /// <param name= "Fields" >fields to export</param>    /// <param name= "Headname" >name of field corresponding to display</param>    /// <param name= "TableName" >Export the name of Excel</param>     Public Static voidexportToExcel (DataTable dataList,string[] fields,string[] headtexts,stringTableName) {exportToExcel (dataList, Fields, Headtexts,string.    Empty, TableName); }    /// <summary>    ///Set Style/// </summary>    /// <param name= "GVW" ></param>    Private Static voidSetstype (GridView GVW) {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=Ten; Gvw. RowStyle.Font.Size=Ten; }    /// <summary>    ///Export data from the GridView to Excel/// </summary>    /// <param name= "GVW" ></param>    /// <param name= "DataList" ></param>    Private Static voidexportToExcel (GridView GVW,stringTitlestringTableName) {        //int coun = Existsregedit (); //string fileName = string.        Format ("Datainfo{0:yyyy-mm-dd_hh_mm}.xls", DateTime.Now); //if (Coun >0)//{        //fileName = string.        Format ("Datainfo{0:yyyy-mm-dd_hh_mm}.xls", DateTime.Now); //    //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7; //}        //Else//{        //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; //    //page.registerstartupscript ("mess", "<script>alert (' The machine does not have any Office software installed ');</script>"); //    //return; //}         for(inti =0; I < GVW. Rows.Count; i++)        {             for(intj =0; J < GVW. HeaderRow.Cells.Count; J + +)            {                //This gives the specified column edit format, the digital output as text, to prevent the digital overflowGvw. Rows[i]. CELLS[J]. Attributes.Add ("style","vnd.ms-excel.numberformat:@"); }} HttpContext.Current.Response.Buffer=true;        HttpContext.Current.Response.ClearContent ();        HttpContext.Current.Response.ClearHeaders (); //fileName = string. Format ("Datainfo{0:yyyy-mm-dd_hh_mm}.xls", DateTime.Now);HttpContext.Current.Response.AppendHeader ("content-disposition","attachment;filename="+ TableName + System.Web.HttpUtility.UrlEncode (title) + DateTime.Now.ToShortDateString () +". xls"); HttpContext.Current.Response.Charset="UTF-8"; HttpContext.Current.Response.ContentEncoding= System.Text.Encoding.GetEncoding ("UTF-8"); HttpContext.Current.Response.ContentType="Application/vnd.ms-excel"; StringWriter TW=NewSystem.IO.StringWriter (); HtmlTextWriter HW=NewSystem.Web.UI.HtmlTextWriter (TW); Gvw.        RenderControl (HW); if(!string. IsNullOrEmpty (title)) {HttpContext.Current.Response.Write ("<b><center><font size=3 face=verdana color= #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; }    //Check the version of Office     Public Static intExistsregedit () {intifused =0; RegistryKey RK=Registry.localmachine; RegistryKey Akey= RK. OpenSubKey (@"software\microsoft\office\11.0\excel\installroot\");//Query 2003RegistryKey akey07 = rk. OpenSubKey (@"software\microsoft\office\12.0\excel\installroot\");//QueryRegistryKey akeytwo = rk. OpenSubKey (@"software\kingsoft\office\6.0\common\");//Query wps//Check if the machine is installed Office2003        if(Akey! =NULL)        {            stringFILE03 = Akey. GetValue ("Path").            ToString (); if(File.exists (file03 +"Excel.exe") ) {ifused+=1; }        }        //Check if the machine is installed Office2007//if (akey07! = null)//{        //string file07 = Akey. GetValue ("Path").        ToString (); //if (file.exists (file07 + "Excel.exe"))//    {        //ifused + = 2; //    }        //}        ////Check if WPS is installed on this machine        //if (akeytwo! = null)//{        //string filewps = Akeytwo. GetValue ("InstallRoot").        ToString (); //if (file.exists (filewps + @ "\office6\et.exe"))//    {        //ifused + = 4; //    }        //}        returnifused; }

There are a lot of similar codes on the Web, and the code is also annotated and understandable.

The special aspect of my code is the ability to directly display numbers in text (and also to find solutions on the web) that I have directly integrated.

The two arrays you enter represent the field names and the Chinese names that appear in Excel.

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.