SqlDataReader或DATATABLE DATASET 到EXCEL

 public void GetExcel(System.Data.SqlClient.SqlDataReader dtData)
    {
        System.Web.UI.WebControls.GridView dgExport = null;
        // 当前对话
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        // IO用于导出并返回excel文件
        System.IO.StringWriter strWriter = null;
        System.Web.UI.HtmlTextWriter htmlWriter = null;

        if (dtData != null)
        {
            // 设置编码和附件格式
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("gb2312");

            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" +Session["Project_Id"]+ "项目名单.xls"); //定义输出文件和文件名
            curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;

            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;

            curContext.Response.Charset = "";

            // 导出excel文件
            strWriter = new System.IO.StringWriter();
            htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

            dgExport = new System.Web.UI.WebControls.GridView();
            dgExport.DataSource = dtData;
            dgExport.AllowPaging = false;
            dgExport.DataBind();

            dgExport.RenderControl(htmlWriter);
            curContext.Response.Write(strWriter.ToString());
            curContext.Response.End();
        }


    }

posted @ 2008-06-17 18:59  搞IT的狐狸  阅读(764)  评论(1编辑  收藏  举报