项目中最近用到了GridView导出Word的例子,但是无法导出成功。后来在下面地址找到了解决方案:http://www.cnblogs.com/jeff377/archive/2008/05/17/1201192.html。这里面是vb版的,我改成了C#版,具体的问题以及原因我就不赘述了,下面附上我的C#代码,希望对一些朋友有帮助:
模板:
public class ExportToExcel:WebPartPage
{
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
if (IsVerifyRender)
{
base.VerifyRenderingInServerForm(control);
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
private bool _IsVerifyRender=true;
public bool IsVerifyRender
{
get { return _IsVerifyRender; }
set { _IsVerifyRender = value; }
}
public override bool EnableEventValidation
{
get
{
if (IsVerifyRender)
{
return base.EnableEventValidation;
}
else
{
return false;
}
}
set
{
base.EnableEventValidation = value;
}
}
}
使用:
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
((ExportToExcel)gvwQuestion.Page).IsVerifyRender = false;
gvwQuestion.RenderControl(oHtmlTextWriter);
Export("application/ms-excel", QuestionExcelName, oStringWriter);