GridView 导出为Word和Execl文件

1、在有页面中添加一个GridView1,添加一个button
2、在页面加载事件中为GridView1填充数据
3、button 控件的Click事件中添加如下代码:
  string style = @"<style> .text { mso-number-format:\@; } </script> ";
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode("word.doc"));
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            Response.ContentType = "application/vnd.word";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            DataList1.RenderControl(htmlWrite);
            Response.Write(style);
            Response.Write(stringWrite.ToString());
            Response.End();
这样就可以把GridView中的数据导出为 Word文档了
要导出为Execl文件只要把 Response.ContentType = "application/vnd.word";
该为Response.ContentType = "application/vnd.xls";
当然你要把Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode("word.doc"));
改为Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode("Execl.xls"));

posted on 2007-03-24 22:59  myer  阅读(658)  评论(0编辑  收藏  举报

导航