您的位置:首页 > 编程语言 > ASP

一种把ASP.net网页数据导出到外部文件的方法

2008-01-19 01:11 429 查看
外部文件可以是.doc、.xls、.txt、.htm.

源地址在http://www.516kd.com/?tid=116,是一位网名wangwei的Blog上的。

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear(); //清除缓冲区流中的所有内容输出
Response.Buffer = true; //
Response.Charset = "GB2312"; //设置输出流的http字符集
//保存附件用"attachment;filename=bang.xls";在线打开用"online;filename=bang.xls"
//可以是.doc、.xls、.txt、.htm、
Response.AppendHeader("Content-Disposition", "attachment;filename=bang.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
//设置输出文件类型为excel文件。保存为word时,应为"application/ms-word"
//可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html、或其他浏览器可直接支持文档 
Response.ContentType = "application/ms-excel";
this.EnableViewState = false; //关闭保存视图状态
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);
this.GridView1.RenderControl(oHtmlTextWriter); //将DataGrid(dgBang)中的内容输出到oHtmlTextWriter
Response.Write(oStringWriter.ToString());
Response.End();//将当前所有缓冲的输出发送到客户端,并停止该页执行
}
//这个必须写
public override void VerifyRenderingInServerForm(Control control)
{
}

另外,ASP页面头代码需要修改为

<%@ Page Language="C#" EnableEventValidation="false">

否则会提示Gridview中的控件GV2需要在runat=server内。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: