淡水求咸

博客园已经停止更新,请移步 http://lovecjh.com/

导航

ExportToExcel(工作笔记)

一、DataTable导出到Excel

(1)DataTableToExcel 函数

    /// <summary>
    /// Datatable输出到Excel
    /// </summary>
    /// <param name="dt">DataTable数据集</param>
    /// <param name="FileName">Excel文件名</param>
    protected void DataTableToExcel(DataTable dt, string FileName)
    {
        System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();
        gv.DataSource = dt;
        gv.DataBind();
//设置网络输出流的HTTP字符集为UTF-8(具体格式看自己的网站格式),Current为当前 HTTP 请求获取 HttpContext 对象 HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
//设置输出流HTTPMIME类型为excel HttpContext.Current.Response.ContentType = "application/ms-excel";
//将HTTP头添加到输出流 HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName + ".xls");
//不保存该控件的视图状态 //ctl.Page.EnableViewState = false; System.IO.StringWriter sw = new System.IO.StringWriter();
//将文本写入到输出流 System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); //将服务器控件的内容输出到HtmlTextWriter对象中

gv.RenderControl(hw);
//StringWriter.ToString返回包含迄今为止写入到当前 StringWriter 中的字符的字符串 HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); }

(2)应用(这里以DataSet转DataTable)

 DataSet ds = DAO.GetEvaluationStationBasicInfoByCondition(InfoBean);
 DataTableToExcel(ds.Tables[0], "data");

 

posted on 2013-05-22 19:38  深圳彦祖  阅读(2868)  评论(0编辑  收藏  举报