桃荷菊梅

博客园 首页 新随笔 联系 订阅 管理
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Configuration;
namespace PeterTools
{
   public class ToExcelClass
    {
        //在导出Excel这个重写函数会用到
        //public override void VerifyRenderingInServerForm(Control control)
        //{
        //    // Confirms that an HtmlForm control is rendered for
        //}

        /// <summary>
        /// GridView导出Excel(可以导出当前页,也可以导出所有页)
        /// </summary>
        /// <param name="ctl">GridView的ID</param>
        /// <param name="FileName">要导出的Excel的名称(ex:nowpage.xls)</param>
        /// ex:ToExcel(this.GridView1,"aa.xls");
        public void ToExcel(Control ctl, string FileName)
        {
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/ms-excel";//导出word只需做此改动"application/ms-word"
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" +HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8));
            ctl.Page.EnableViewState = false;
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            ctl.RenderControl(htw);
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }
        public void AllPagesToExcel(GridView GV, string strFilmName, DataTable dt)//"AllPages.xls"
        {
            GV.AllowPaging = false;
            GV.AllowSorting = false;
            GV.DataSource = dt.DefaultView;
            GV.DataBind();
            ToExcel(GV, strFilmName);
            GV.AllowPaging = true;
            GV.AllowSorting = true;
            GV.DataSource = dt.DefaultView;
            GV.DataBind();
        }
    }
posted on 2008-08-01 15:13  桃荷菊梅  阅读(196)  评论(0编辑  收藏  举报