Asp. NET tip: Output the DataGrid control to an Excel file

Source: Internet
Author: User
Tags bind
Asp.net|datagrid|datagrid Control |excel| Tips

A demo that outputs a DataGrid control to an Excel file.

Generate Excel file #region build Excel file
public void Settoexcel ()
{
//             Response.Clear ();
//            response.buffer= true;  
//            response.charset= "Utf-8";
   
    if (eformsn. text== "")
    {
        datagrid1.visible=false;
        label1.text= "To enter Excel, please input the declaration number!";
        label1.visible=true;
   }
    Else
    {
        dl. DATASOURCE=DB ("Query", "SELECT * from Msi_eol_list_line where eformsn=" +eformsn.) text+ "ORDER by Eformsn"). Tables[0]. DefaultView;
        DL. DataBind ();

This line is very important, the attachment parameters are downloaded as an attachment, you can change the online to open
Filename=fileflow.xls Specifies the name of the output file, noting that its extension name matches the specified file type, which can be:. doc. xls. txt. htm

Response.appendheader ("Content-disposition", "Attachment;filename=eol_" +eformsn. text+ ". xls");
Response.contentencoding=system.text.encoding.getencoding ("Utf-8");

RESPONSE.CONTENTTYPE Specifies that file types can be Application/ms-excel,application/ms-word, application/ms-txt,application/ Ms-html or other browsers can directly support the document file
Response.ContentType = "Application/ms-excel";
Dl. EnableViewState = false;

System.IO.StringWriter ostringwriter = new System.IO.StringWriter ();
System.Web.UI.HtmlTextWriter ohtmltextwriter = new System.Web.UI.HtmlTextWriter (ostringwriter);

Bind the target data to the input output
This indicates that you can also bind the DataGrid, or other support obj, if you output this page. RenderControl () Control of attributes
Dl. RenderControl (Ohtmltextwriter);
This. Databind.rendercontrol (Ohtmltextwriter);
Response.Write (Ostringwriter.tostring ());
Response.End ();
}
}
#endregion



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.