从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();
}