Implemented in the following button click event:
private void btnMIME_Click(object sender, System.EventArgs e)
{
BindData();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename="
+ HttpUtility.UrlEncode("Download file.xls",Encoding.UTF8 ) );
//If the output is Word, modify it to the following code
//Response.ContentType = "application/ms-word"
//Response.AddHeader("Content-Disposition", "inline;filename=test.doc")
StringBuilder sb=new StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
sb.Append("<html><body>");
dgShow.RenderControl(hw);
sb.Append("</body></html>");
Response.Write(sb.ToString());
Response.End();
}
Note: 1. If there is a button column in the DataGrid, it should be hidden before exporting.
2. If the DataGrid has paging, and you want to print all the data, you should cancel the paging first.