Ways to export excel in ASP. NET: Export Excel using Response

Source: Internet
Author: User

Method One: Export with the StringBuilder method

The method is to write all the data in HTML to StringBuilder, and then export it through response.

People who are familiar with HTML format can change into various formats.

List<u> objlist =NewList<u>(); Objlist= BLL. GetInfo ();//reading DataStringBuilder SB=NewStringBuilder (); Sb. Append ("<style type=\ "Text/css\" >"); Sb. Append ("<!--"); Sb. Append (". Text"); Sb. Append ("{mso-style-parent:style0;"); Sb. Append ("font-size:10.0pt;"); Sb. Append ("font-family:\ "Arial Unicode ms\", Sans-serif;"); Sb. Append ("mso-font-charset:0;"); Sb. Append (@"mso-number-format:\@;"); Sb. Append ("Text-align:center;"); Sb. Append ("border:.5pt solid black;"); Sb. Append ("White-space:normal;}"); Sb. Append (" -"); Sb. Append ("</style>"); Sb. Append ("<table cellspacing=\ "0\" rules=\ "all\" border=\ "1\" style=\ "border-collapse:collapse;\" >"); Sb. Append ("<tr align=\ "Center\" style=\ "font-weight:bold;\" >"); Sb. Append ("<td>ID</td><td> user name </td><td> real name </td><td> province </td><td> Registration Time </TD"); Sb. Append ("</tr>"); foreach(U Iteminchobjlist) {sb. Append ("<tr align=\ "Center\" ><td>"+ Item.id +"</td><td>"+ Item.uname +"</td><td>"+ Item.rname +"</td><td>"+ Item.proid +"</td><td>"+ Item.regdate +"</td></tr>"); } sb. Append ("</table>");          System.Web.HttpContext.Current.Response.Clear (); System.Web.HttpContext.Current.Response.Charset="GB2312"; //System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; //Add header information, specify a default file name for the file download/Save As dialog boxSystem.Web.HttpContext.Current.Response.AddHeader ("content-disposition","attachment; Filename=myu.xls"); //Add header information, specify file size, and allow the browser to display download Progress//System.Web.HttpContext.Current.Response.AddHeader ("Content-length", sb.)           ToString ()); //specifies that a stream is returned that cannot be read by the client and must be downloadedSystem.Web.HttpContext.Current.Response.ContentType ="Application/ms-excel"; //send the file stream to the clientSystem.Web.HttpContext.Current.Response.Write (sb.)          ToString ()); //Stop the execution of a pageSystem.Web.HttpContext.Current.Response.End (); 

Method Two: An export method with StringWriter

The format of the method is not easy to change the method with the same principle as above is to write the data into the StringWriter and let the export

As is known to all, Respone.write () is the output HTML streaming program to the user. Considering that a standard Web page is presented in a variety of ways,
For example:
<meta http-equiv= "Content-type" content= "text/html; charset=utf-8" />This is the output of the HTML stream as a standard Web page

<meta http-equiv= "Content-type" content= "Application/vnd.ms-excel">
<meta http-equiv= "Content-disposition" content= "attachment; Filename=ex.xls> This is the HTML stream that is exported as an attachment, and the data is stored in the Ex.xls form. ^_^

Then we in the form of encoding how to display ^_^ (now write VB, given is also the case of VB)
1Dim _datastringwriter as StringWriter = New StringWriter defines a StringWriter object
2 _datastringwriter.witeline ("Firstfieldname" +Controlchars.tab+ "Secondfieldname") add name to each column of Excel table output
3 Remove the data from the data "container". For example
Dim DT as New DataTable
For i as Integer = 0 to dt. Rows.count-1 Then
_datastringwriter.witeline (DT (i) (0) +Controlchars.tab+ DT (i) (1))
Next
4Response.AddHeader ("content-disposition", "attachment; Filename= "& FileName)
Response.ContentType = "Application/vnd.ms-excel"
response.contentencoding = System.Text.Encoding.Unicode
5Response.Write (_datastringwriter) output HTML stream
Response.End ()
The above can be implemented to import data into an Excel table, if you need to import word Response.ContentType = "application/vnd.ms-excel" in the change to Response.ContentType = " Application/vnd.ms-word "can. But note that the filename should also change, Xx.xls or Xx.doc

Method Three: DataTable export

This method is exported response line, you can add the corresponding line according to your own needs.

/// <summary>    ///data in a DataTable is exported to Excel and downloaded/// </summary>    /// <param name= "DT" >the DataTable to export</param>    /// <param name= "FileType" >type</param>    /// <param name= "FileName" >the file name of Excel</param>     Public voidCreateexcel (DataTable DT,stringFileType,stringFileName)        {response.clear (); Response.Charset="UTF-8"; Response.Buffer=true; Response.ContentEncoding= System.Text.Encoding.GetEncoding ("GB2312"); Response.appendheader ("content-disposition","attachment;filename=\ ""+ System.Web.HttpUtility.UrlEncode (FileName, System.Text.Encoding.UTF8) +". Xls\ ""); Response.ContentType=FileType; stringColheaders =string.        Empty; stringLs_item =string.        Empty; Datarow[] Myrow=dt.        Select (); inti =0; intCL =dt.        Columns.count; foreach(DataRow rowinchmyrow) {             for(i =0; I < CL; i++)            {                if(i = = (CL-1))                {
Ls_item+ = Row[i]. ToString () +"\ n"; } Else {
Change Grid Ls_item+ = Row[i]. ToString () +"\ t"; } } //write on one lineResponse.Output.Write (Ls_item); Ls_item=string. Empty; } Response.Output.Flush (); Response.End (); }

How to export excel in ASP. NET: Export Excel using response

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.