asp.net中GridView匯出資料

發表於2010-12-31
 ///
        /// 重寫VerifyRenderingInServerForm方法(不重寫可能會報錯)
        ///

        ///
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        ///
        /// 匯出事件,呼叫匯出方法
        ///

        ///
        ///
        protected void btnExport_Click(object sender, EventArgs e)
        {          
            Export("application/excel",fileName);
        }

 

 

 

    ///模式化特殊元素將服務控制元件改為Literal使其可以輸出

        public void PrepareGridViewForExport(Control gv)  

      {
            LinkButton lb = new LinkButton();
            Literal l = new Literal();
            string name = String.Empty;

            for (int i = 0; i < gv.Controls.Count; i++)
            {

                if (gv.Controls[i].GetType() == typeof(LinkButton))
                {
                    l.Text = (gv.Controls[i] as LinkButton).Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                else if (gv.Controls[i].GetType() == typeof(DropDownList))
                {
                    l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                else if (gv.Controls[i].GetType() == typeof(CheckBox))
                {
                    l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                else if (gv.Controls[i].GetType() == typeof(ImageButton))
                {
                    l.Text = "圖片";
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }
                if (gv.Controls[i].HasControls())
                {
                    PrepareGridViewForExport(gv.Controls[i]);
                }
            }
        }
   

    ///匯出方法

    ///FileType匯出型別 application/excel匯出excel檔案word匯出為word文件

    ///FileName 檔名稱

        public void Export(string FileType, string FileName)
        {

            string style. = @"

相關文章