DataGrid导出Excel

用sql生成数据库集,绑定在 一个datagrid上,然后这样:

public void ToExcel(System.Web.UI.Control ctl)  
{
    
// HttpContext.Current.Response.Charset ="GB2312";    
    HttpContext.Current.Response.Charset ="";
    HttpContext.Current.Response.AppendHeader(
"Content-Disposition","attachment;filename=money.xls");
                
    HttpContext.Current.Response.ContentEncoding 
=System.Text.Encoding.GetEncoding("GB2312"); 
    HttpContext.Current.Response.ContentType 
="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
    ctl.Page.EnableViewState =false;            
    System.IO.StringWriter  tw 
= new System.IO.StringWriter() ;
    System.Web.UI.HtmlTextWriter hw 
= new System.Web.UI.HtmlTextWriter (tw);
    ctl.RenderControl(hw);
    HttpContext.Current.Response.Write(tw.ToString());
    HttpContext.Current.Response.End();
}

用法:ToExcel(datagrid1);
注意,不要分页,分页会不好用。
posted @ 2008-07-18 23:17  angushine  阅读(160)  评论(0编辑  收藏  举报