Excel (. xls) file for export/import rules under ASP.net

Source: Internet
Author: User
Data in a DataTable export Excel file


///<summary>


///exports data from a DataTable to a specified Excel file


///</summary>


///<param name= "page" >web pages object </param>


///<param name= "tab" > DataTable object containing exported data </param>


///<param name= name of "FileName" >excel file </param>


public static void Export (System.Web.UI.Page page,system.data.datatable tab,string FileName)


{


System.Web.HttpResponse HttpResponse = page. Response;


System.Web.UI.WebControls.DataGrid datagrid=new System.Web.UI.WebControls.DataGrid ();


Datagrid.datasource=tab. DefaultView;


datagrid.allowpaging = false;


dataGrid.HeaderStyle.BackColor = System.Drawing.Color.Green;


dataGrid.HeaderStyle.HorizontalAlign = Horizontalalign.center;


DataGrid.HeaderStyle.Font.Bold = true;


Datagrid.databind ();


Httpresponse.appendheader ("Content-disposition", "attachment;filename=" +httputility.urlencode (filename, SYSTEM.TEXT.ENCODING.UTF8)); Filename= "*.xls";


httpresponse.contentencoding=system.text.encoding.getencoding ("GB2312");


Httpresponse.contenttype = "Application/ms-excel";


System.IO.StringWriter tw = new System.IO.StringWriter ();


System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (TW);


Datagrid.rendercontrol (HW);





string filePath = page. Server.MapPath ("..") + "Files" +filename;


System.IO.StreamWriter SW = System.IO.File.CreateText (FilePath);


SW. Write (TW. ToString ());


SW. Close ();


Downfile (Httpresponse,filename,filepath);





Httpresponse.end ();


}


private static bool Downfile (System.Web.HttpResponse response,string filename,string fullpath)


{


Try


{


Response.ContentType = "Application/octet-stream";





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.