Dt:datatable
Strfile:filename
Strext:type
private void Gridexport (DataTable dt, String strfile, String strext)
{
String strapptype = "";
Switch (strext)
{
Case "XLS":
Strapptype = "Application/ms-excel";
Break
Case "Doc":
Strapptype = "Application/ms-word";
Break
Case "TXT":
Strapptype = "Application/ms-txt";
Break
Case "HTML":
Case "htm":
Strapptype = "application/ms-html";
Break
Default:return;
}
GridView MyGridView = new GridView ();
Mygridview.datasource = DT;
Mygridview.databind ();
HttpContext.Current.Response.Clear ();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader ("Content-type", "text/html; charset=gb2312 ");
HttpContext.Current.Response.AppendHeader ("Content-disposition", String. Format ("attachment;filename={0}.{ 1} ", Httputility.urlencode (strfile,encoding.getencoding (" GB2312 ")), Strext));
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312");
HttpContext.Current.Response.ContentType = Strapptype;
MyGridView.Page.EnableViewState = false;
Second, define an input stream
System.Globalization.CultureInfo Mycitrad = new System.Globalization.CultureInfo ("ZH-CN", true);
System.IO.StringWriter ostringwriter = new System.IO.StringWriter (Mycitrad);
System.Web.UI.HtmlTextWriter ohtmltextwriter = new System.Web.UI.HtmlTextWriter (ostringwriter);
Third, bind the target data to the input stream output
Mygridview.rendercontrol (Ohtmltextwriter);
HttpContext.Current.Response.Write (Ostringwriter.tostring ());
HttpContext.Current.Response.End ();
}