将数据控件(如GridView)的内容转化成Excel格式文件
Response.Clear(); //清空输出流
Response.Buffer = true; //开启缓冲输出
Response.Charset = "GB2312"; //输出字符集中文
Response.AppendHeader("Content-Disposition", "attachment;filename=你要存成的文件名字.xls");
// 如果设置为 GetEncoding("GB2312");否则导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter); //GridView 内容输出到流,其他数据组件类似
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
注意:另外一定要加上下面的方法 这个是重写的注册方法,否则会报错
public override void VerifyRenderingInServerForm(Control control)
{
Response.Buffer = true; //开启缓冲输出
Response.Charset = "GB2312"; //输出字符集中文
Response.AppendHeader("Content-Disposition", "attachment;filename=你要存成的文件名字.xls");
// 如果设置为 GetEncoding("GB2312");否则导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter); //GridView 内容输出到流,其他数据组件类似
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
注意:另外一定要加上下面的方法 这个是重写的注册方法,否则会报错
public override void VerifyRenderingInServerForm(Control control)
{
}