您的位置:首页 > 其它

导出Excel(防止导出整个页面)

2012-03-23 15:31 351 查看
前台页面放一个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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: