从DataGrid输出数据到Excel
方法很简单,只是将DataGrid的内容输出到HtmlTextWriter流,再将流作为附件让用户下载或者用Excel打开.
此方法虽然简单,但能实现功能.
private void button_OutExcel_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
this.EnableViewState = false;
//定义输入流
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter txtwriter = new HtmlTextWriter(writer);
//将DataGrid中的内容输出到txtwriter流中
this.DataGrid1.RenderControl(txtwriter);
//作为附件输出,filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
Response.ContentType = "application/ms-excel"; //ContentType指定文件类型 可以为application/ms-excel application/ms-word application/ms-txt application/ms-html 或其他浏览器可直接支持文档
Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls"); //下载
//Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
Response.Write(writer);
Response.End();
}
==================
实例:
//将DataGrid(dgBang)中的内容输出到Excel文件中,可以选择保存路径,并取名字
private void GridToExcel_Click(object sender, System.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.dgBang.RenderControl(oHtmlTextWriter); //将DataGrid(dgBang)中的内容输出到oHtmlTextWriter
Response.Write(oStringWriter.ToString());
Response.End();//将当前所有缓冲的输出发送到客户端,并停止该页执行
}