1. 程式人生 > >匯出Excel(防止匯出整個頁面)

匯出Excel(防止匯出整個頁面)

前臺頁面放一個GridView什麼的就不說了,要注意的是在

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="ReferPriceIndex.aspx.cs"EnableEventValidation="false"
    Inherits="ZTE.Fol.Fund.UI.Web.InsideTrade.ReferPrice.ReferPriceIndex" %>

標籤裡面加紅色字型的那個屬性

同時後臺加上

/// <summary>
        /// 內容摘要:重寫空的VerifyRenderingInServerForm方法,避免在匯出Excel檔案的時候出現
        /// “……必須放在具有 runat=server 的窗體標記內”的異常
        /// 另外說明:
        /// 在asp.net2.0中,控制元件的校驗嚴格了,
        /// RenderControl程式碼只有走正常流程在render方法中它自己呼叫才能成功,
        /// 在自己寫的事件方法中呼叫就會出現這個錯誤。
        /// </summary>
        /// <param name="control">提交控制元件</param>
        public override void VerifyRenderingInServerForm(Control control)
        {
        }// end VerifyRenderingInServerForm

這兩個地方都加上,可以防止匯出excel的時候匯出整個頁面

下面將將具體方法貼出來

/// <summary>
        /// 匯出資料到EXCEL檔案
        /// </summary>
        /// <param name="page">頁面</param>
        /// <param name="gvExcel">匯出的GrivView</param>
        private void ExportToExcel(System.Web.UI.Page page, GridView dgExcel)
        {
            try
            {
                foreach (GridViewRow row in dgExcel.Rows)
                {
                    foreach (TableCell cell in row.Cells)
                    {
                        cell.Style.Add("vnd.ms-excel.numberformat", "@");//給表格內容設定樣式
                    } // end foreach (TableCell cell in row.Cells)

                } // end foreach (GridViewRow row in dgExcel.Rows)

                string fileName = "OutData.xls";
                page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "utf-8";
                Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.ContentType = "application/ms-excel";

                dgExcel.Page.EnableViewState = false;
                System.IO.StringWriter tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
                dgExcel.RenderControl(hw);

                // 輸出DataGrid內容
                Response.Write(tw.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                ZTE.Fol.Framework.Common.Util.WebUtil.MessageBox(this.Page, ex.Message);
            }
        }