导出grivied excel

using System;
using System.Data;
using System.Configuration;
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.IO;
using System.Text;


namespace WFWMS.Lib
{
    public class GridViewExportExcel
    {
       

HttpResponse Response = null;
        public GridViewExportExcel(HttpResponse response)
        {
            Response = response;
        }
        /// <summary>
        /// 将GridView里的数据导入到Excel文件中,并另存文档,无隐藏列
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="gv"></param>
        public void Export(string FileName, GridView gv)
        {
            Export(FileName, gv, null, "GB2312");
        }
        public void Exporthtml(string FileName, System.Web.UI.HtmlControls.HtmlTable gv)
        {
            Exporthtml(FileName, gv, null, "GB2312");
        }

        public void Export2(string FileName, GridView gv)
        {
            Export2(FileName, gv, null, "GB2312");
        }
        /// <summary>
        /// 将GridView里的数据导入到Excel文件中,并另存文档,无隐藏列
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="gv"></param>
        public void Export(string FileName, GridView gv, string strEncode)
        {
            Export(FileName, gv, null, strEncode);
        }
        /// <summary>
        /// 将GridView里的数据导入到Excel文件中,并另存文档,需要隐藏列
        /// </summary>
        /// <param name="FileName">文件名称</param>
        /// <param name="GridViewTeacher">要导出数据的GridView</param>
        public void Export(string FileName, GridView gv, int[] hidColumns, string strEncode)
        {
            //去除分页功能
            if (gv.AllowPaging == true)
            {
                gv.AllowPaging = false;
                gv.DataBind();
            }
            gv.BorderWidth = 1;
            //替换服务器控件
            PrepareControlForExport(gv);

            //用来控制添加,删除,编辑等按钮不输出
            if (hidColumns != null)
            {
                foreach (int i in hidColumns)
                {
                    gv.Columns[i].Visible = false;
                }
            }
            Response.Charset = strEncode;
            Response.ContentEncoding = Encoding.GetEncoding(strEncode);
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.GetEncoding(strEncode)).ToString() + ".xls");
            Response.ContentType = "application/ms-excel";//导出excel文件
            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
            gv.Page.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            gv.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        /// <summary>
        /// 将GridView里的数据导入到Excel文件中,并另存文档,需要隐藏列
        /// </summary>
        /// <param name="FileName">文件名称</param>
        /// <param name="GridViewTeacher">要导出数据的GridView</param>
        public void Export2(string FileName, GridView gv, int[] hidColumns, string strEncode)
        {
            //去除分页功能
            if (gv.AllowPaging == true)
            {
                gv.AllowPaging = false;
                gv.DataBind();
            }
            gv.BorderWidth = 1;
            //替换服务器控件
            PrepareControlForExport(gv);

            //用来控制添加,删除,编辑等按钮不输出
            if (hidColumns != null)
            {
                foreach (int i in hidColumns)
                {
                    gv.Columns[i].Visible = false;
                }
            }
            Response.Charset = strEncode;
            Response.ContentEncoding = Encoding.UTF8;
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.GetEncoding(strEncode)).ToString() + ".xls");
            Response.ContentType = "application/ms-excel";//导出excel文件
            gv.Page.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            gv.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        public void Exporthtml(string FileName, System.Web.UI.HtmlControls.HtmlTable ht, int[] hidColumns, string strEncode)
        {
            //替换服务器控件
            PrepareControlForExport(ht);

            ////用来控制添加,删除,编辑等按钮不输出
            //if (hidColumns != null)
            //{
            //    foreach (int i in hidColumns)
            //    {
            //        ht.c
            //    }
            //}
            Response.Charset = strEncode;
            Response.ContentEncoding = Encoding.GetEncoding(strEncode);
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.GetEncoding(strEncode)).ToString() + ".xls");
            Response.ContentType = "application/ms-excel";//导出excel文件
            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
            ht.Page.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            ht.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
        }

        #region Export_UTF8 fo ZGR

        //页面上gvData_RowCreated加上以下代码,导出excel不会成为科学记数法。
        //protected void gvData_RowCreated(object sender, GridViewRowEventArgs e)
        //{
        //    for (int c = 0; c < e.Row.Cells.Count; c++)
        //    {
        //        e.Row.Cells[c].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
        //    }
        //}


        public void Export_UTF8(string FileName, GridView gv)
        {
            Export_UTF8(FileName, gv, null);
        }
        public void Export_UTF8(string FileName, GridView gv, int[] hidColumns)
        {
            Export_UTF8(FileName, gv, hidColumns, "application/ms-excel", "xls");
        }
        public void Export_UTF8(string FileName, GridView gv, int[] hidColumns, string ContentType, string FileType)
        {
            if (gv.AllowPaging == true)
            {
                gv.AllowPaging = false;
                gv.DataBind();
            }

            //替换服务器控件
            PrepareControlForExport(gv);

            //用来控制添加,删除,编辑等按钮不输出
            if (hidColumns != null)
            {
                foreach (int i in hidColumns)
                {
                    gv.Columns[i].Visible = false;
                }
            }


            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            Page page = new Page();
            HtmlForm form = new HtmlForm();

            gv.EnableViewState = false;
            page.EnableEventValidation = false;
            page.DesignerInitialize();

            page.Controls.Add(form);
            form.Controls.Add(gv);
            page.RenderControl(htw);

            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = ContentType;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName + "." + FileType);
            Response.Charset = "UTF-8";
            Response.ContentEncoding = Encoding.UTF8;

            Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");

            Response.Write(sb.ToString());

            Response.Write("</body></html>");
            Response.End();
        }
        #endregion

        /// <summary>
        /// 替换服务器控件
        /// </summary>
        /// <param name="control"></param>
        private void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }


        /// <summary>
        /// 页面中的 Panel 导出到 Excel
        /// </summary>
        /// <param name="PanelID"></param>
        /// <param name="res"></param>
        /// <param name="fileName"></param>
        public static void PanelToExcel(Panel PanelID, HttpResponse res)
        {

            res.Clear();
            res.Buffer = true;
            res.Charset = "UTF-8";
            res.AppendHeader("Content-Disposition", "attachment;filename=Sheet.xls");
            res.ContentEncoding = System.Text.Encoding.UTF8;
            res.ContentType = "application/vnd.ms-excel";
            PanelID.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            PanelID.RenderControl(oHtmlTextWriter);
            res.Output.Write(oStringWriter.ToString());
            res.Flush();
            res.End();
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        /// <summary>
        /// 页面中的 Panel 导出到 Word
        /// </summary>
        /// <param name="PanelID"></param>
        /// <param name="res"></param>
        /// <param name="fileName"></param>
        public static void PanelToWord(Panel PanelID, HttpResponse res)
        {
            res.Clear();
            res.Buffer = true;
            res.Charset = "UTF-8";
            res.AppendHeader("Content-Disposition", "attachment;filename=Sheet.doc");
            res.ContentEncoding = System.Text.Encoding.UTF8;
            res.ContentType = "application/vnd.ms-word";
            PanelID.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            PanelID.RenderControl(oHtmlTextWriter);
            res.Output.Write(oStringWriter.ToString());
            res.Flush();
            res.End();
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

    }
}

posted @ 2012-12-10 16:21  洗耳恭听兼烂笔头  阅读(215)  评论(0编辑  收藏  举报