Web项目中导出数据的一个控件类

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Drawing;

namespace WebHJControls

{

    /// <summary>

    /// Export 的摘要说明。

    /// </summary>

    public class WebExport: LinkButton

    {

        public WebExport()

        {

            //

            // TODO: 在此处添加构造函数逻辑

            //

        }

       

        protected override void OnClick(EventArgs e)

        {

            ExportButton_Click();

        }

        /// <summary>

        /// 扩展名,在设置导出文件类型的时候同时设置

        /// </summary>

        private string ExtensionType

        {

            get

            {

                if(ViewState["ExtensionType"] == null)

                    return ".xls";

                return (string)ViewState["ExtensionType"];

            }

            set

            {

                ViewState["ExtensionType"] = value;

            }

        }

 

        /// <summary>

        /// 要导出内容的目标控件ID,如果目标控件的父亲控件不是Page,那么应该从Page下的该控件的根控件开始传入,格式是ParentControlID.ControlID.ControlID...

        /// </summary>

        public string TargetControlID

        {

            get

            {

                if(ViewState["TargetControlID"] == null)

                    return String.Empty;

                return (string)ViewState["TargetControlID"];

            }

            set

            {

                ViewState["TargetControlID"] = value;

            }

        }

        /// <summary>

        /// 文件类型

        /// </summary>

        public ExportFileType FileType

        {

            get

            {

                if(ViewState["ExportFileType"] == null)

                    return ExportFileType.Excel;

                return (ExportFileType)ViewState["ExportFileType"];

            }

            set

            {

                ViewState["ExportFileType"] = value;

                switch(value)

                {

                    case ExportFileType.Excel:

                        this.ExtensionType = ".xls";

                        break;

                    case ExportFileType.Word:

                        this.ExtensionType = ".doc";

                        break;

                    case ExportFileType.html:

                        this.ExtensionType = ".html";

                        break;

                    default:

                        this.ExtensionType = ".xls";

                        break;

                }

            }

        }

        /// <summary>

        /// 导出的文件名

        /// </summary>

        public string ExportFileName

        {

            get

            {

                if(ViewState["ExportFileName"] == null)

                    return "ExportFile";

                return (string)ViewState["ExportFileName"];

            }

            set

            {

                ViewState["ExportFileName"] = value;

            }

        }

        protected override void Render(HtmlTextWriter writer)

        {

            if(Page != null)

            {

                Page.VerifyRenderingInServerForm(this);

            }

            this.CausesValidation = false;

            base.Render (writer);

        }

        private void ExportButton_Click()

        {

            //确保找到控件

            Control c = AnalyseControlID();

            if(c == null)

                return;

            HttpResponse response = HttpContext.Current.Response;

            response.Clear();

            response.Buffer= true;

            response.ContentType = SetContentType();

            response.AddHeader("Content-Disposition", "attachment; filename=" + ExportFileName + ExtensionType + "");

            response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");

            response.Charset = "gb2312";

            EnableViewState = false;

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            ClearControls(c);

            c.RenderControl(oHtmlTextWriter);

            response.Write(oStringWriter.ToString());

            response.End();

        }

        private string SetContentType()

        {

            string contentType = String.Empty;

            switch(FileType)

            {

                case ExportFileType.Excel:

                    contentType = "application/vnd.ms-excel";

                    break;

                case ExportFileType.Word:

                    contentType = "application/vnd.ms-word";

                    break;

                case ExportFileType.html:

                    contentType = "application/txt";

                    break;

            }

            return contentType;

        }

        private Control AnalyseControlID()

        {

            if(Page != null)

            {

                string[] controlIDArray = TargetControlID.Split('.');

                Control c = Page.FindControl(controlIDArray[0]);

                for(int i = 1;i < controlIDArray.Length;i++)

                {

                    c = c.FindControl(controlIDArray[i]);

                }

                return c;

            }

            return null;

        }

        public bool ThumbnailCallback()

        {

            return false;

        }

        /// <summary>

        /// 清除可能产生回发的子控件变成文本控件,如果不这样做的话,调用RenderControl会产生错误

        /// Reference:http://www.c-sharpcorner.com/Code/2003/Sept/ExportASPNetDataGridToExcel.asp

        /// </summary>

        /// <param name="control"></param>

        private void ClearControls(Control control)

        {

            if(control is System.Web.UI.WebControls.Image)

            {

               

                //                string vpath = ((System.Web.UI.WebControls.Image)control).ImageUrl;

                //                Uri baseUri = new Uri(vpath);

                //                string apath =this.Context.Server.MapPath(baseUri.AbsolutePath);

                //                System.Drawing.Image img = System.Drawing.Image.FromFile(apath);

                //                System.Drawing.Image.GetThumbnailImageAbort cbl = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

                //                System.Drawing.Image newimg = img.GetThumbnailImage(100,150,cbl,IntPtr.Zero);               

                //newimg.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);

            }

            if(control.ClientID.Equals("Photo"))

            {

               

            }

            for (int i=control.Controls.Count -1; i>=0; i--)

            {

                ClearControls(control.Controls[i]);

            }

            if (!(control is TableCell))

            {

                if (control.GetType().GetProperty("SelectedItem") != null)

                {

                    if(control.Parent != null)

                    {

                        LiteralControl literal = new LiteralControl();

                        control.Parent.Controls.Add(literal);

                        try

                        {

                            literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null);//如果是处于选中状态的项

                       

                        }

                        catch

                        {

                        }

                        control.Parent.Controls.Remove(control);

                    }

                }

                else if (control.GetType().GetProperty("Text") != null)

                {

                    if(control.Parent != null)

                    {

                        LiteralControl literal = new LiteralControl();

                        control.Parent.Controls.Add(literal);

                        literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control,null);

                        control.Parent.Controls.Remove(control);

                    }

                }

            }

            return;

        }

    }

    /// <summary>

    /// 导出的文件类型

    /// </summary>

    public enum ExportFileType

    {

        Word = 1,

        Excel = 2,

        html = 3

    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值