Microsoft . 技术之路...

—— 专注于微软技术, 分享是快乐的源泉......
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

DataGrid输出文件的几种方法

Posted on 2007-06-22 11:00  赣江源  阅读(209)  评论(0编辑  收藏  举报
从DataGrid输出文件到Excel、Word和Text文件使用这样输出还是很高效的。

1、输出到Excel:
            Response.Clear();
            Response.AddHeader(
"content-disposition""attachment;filename=FileName.xls");
            Response.Charset 
= "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType 
= "application/vnd.xls";
            System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite 
= new HtmlTextWriter(stringWrite);
            myDataGrid.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();

2、输出到Word文档
            Response.Clear();
            Response.AddHeader(
"content-disposition""attachment;filename=FileName.doc");
            Response.Charset 
= "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType 
= "application/vnd.word";
            System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite 
= new HtmlTextWriter(stringWrite);
            myDataGrid.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();

3、输出到文本文件
            Database db = DatabaseFactory.CreateDatabase(); 
            DBCommandWrapper selectCommandWrapper 
= db.GetStoredProcCommandWrapper("sp_GetLatestArticles"); 
            
            DataSet ds 
= db.ExecuteDataSet(selectCommandWrapper); 

            StringBuilder str 
= new StringBuilder(); 

            
for(int i=0;i<=ds.Tables[0].Rows.Count - 1; i++
            {
                
for(int j=0;j<=ds.Tables[0].Columns.Count - 1; j++
                {
                    str.Append(ds.Tables[
0].Rows[i][j].ToString()); 
                }
                str.Append(
"<BR>");
            }

            Response.Clear();
            Response.AddHeader(
"content-disposition""attachment;filename=FileName.txt");
            Response.Charset 
= "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType 
= "application/vnd.text";
            System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite 
= new HtmlTextWriter(stringWrite);
            Response.Write(str.ToString());
            Response.End();