注意这种方法,导出的excel没有网格线
当在导出Execl或Word的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
下面的2中方法是在网上找到的,没有应用:
1.修改web.config(不推荐)
<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportWordByIO.aspx.cs" Inherits="_Default" EnableEventValidation = "false" %>
我自己应用的处理方法:
还有一种情况,是因为导出到excel文件的控件中包含内部控件(比如linkbutton,button,超链接等),需要将这些内部控件转换为文本才可以。
在导出数据之前,使用ClearControls()方法清除内部控件。
/// <summary>
/// 导出Excel功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Btn_Excel_Click(object sender, EventArgs e)
{
//导出全部数据,取消分页
GridView_BatchQuality.AllowPaging = false;
GridView_BatchQuality.ShowFooter = false; BindGridView(); Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("导出" + System.DateTime.Now.Date.ToString("yyyyMMdd")) + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.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); ClearControls(GridView_BatchQuality);
this.GridView_BatchQuality.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End(); //还原分页显示
GridView_BatchQuality.AllowPaging = true;
GridView_BatchQuality.ShowFooter = true;
BindGridView();
} /// <summary>
/// GridView如果需要实现导出Excel功能,则该函数需要重载
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
} /// <summary>
/// 清除控件中的所有控件,以便导出Excel
/// </summary>
/// <param name="control"></param>
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
} if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != 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)
{
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;
}