62,041
社区成员
发帖
与我相关
我的任务
分享
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2321";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
Session["output数据"] = this.ObjectDataSource1.Select(); //使用当前数据源的Select()方法提取数据
ClientScript.RegisterStartupScript(this.GetType(), "导出",
string.Format("window.open(\"{0}\",\"_blank\");", this.Page.ResolveUrl("~/output.aspx"))
, true);
这样,你的另一个页面 output.aspx 读取 Session["output数据"] 绑定到 GridView 上,再“导出excel”。由于这个页面是从当前页面copy来的,然后简化的,因此其实很容易生成。
大多数浏览器都有这样的功能,如果一个新弹出的页面标记了 Content-Disposition 头,在页面下载完毕之后,页面会自动关闭。不需要你再 output.aspx 页面中写关闭页面的脚本。
private void DataSetToExcel(string FileName)
{
//创建获取要导出的excel
DataSet ds = CreatDataSet();
string style = "<style>td{mso-number-format:\"\\@\";}</style>";//防止导出excel时将以0开头的全数字数据的0去掉
DateTime now = System.DateTime.Now;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid dg = new DataGrid();
dg.DataSource = ds;
dg.DataBind();
dg.RenderControl(htmlWrite);
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(now.ToString() + ".xls"));
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}