◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
asp.net网页输出word
Post by iambbp, 2009-5-4, Views:asp.net网页输出word
我的毕设是做一个题库系统,自动组卷并且可以输出为doc文件。
asp.net网页输出word的c#代码:
C# code
/**//// <summary>
/// 将Web控件导出
/// </summary>
/// <param name="source">控件实例</param>
/// <param name="type">类型:Excel或Word</param>
public void ExpertControl(System.Web.UI.Control source, DocumentType type)
{
//设置Http的头信息,编码格式
if (type == DocumentType.Excel)
{
//Excel
Response.AppendHeader("Content-Disposition","attachment;filename=result.xls");
Response.ContentType = "application/ms-excel";
}
else if (type == DocumentType.Word)
{
//Word
Response.AppendHeader("Content-Disposition","attachment;filename=result.doc");
Response.ContentType = "application/ms-word";
}
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
//关闭控件的视图状态
source.Page.EnableViewState =false;
//初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter);
//输出
Response.Write(writer.ToString());
Response.End();
}
//文档类型
public enum DocumentType
{
Word,
Excel
}
调用方法:
ExpertControl(this, DocumentType.Word);
这是将整个页面导出为Word
//this可以为具体的控件如datagrid/dataList或page表示当前页,DocumentType为导出的文件格式(Excel/word)
注意:当为datagrid或dataList控件时,在导出Excel/word文件时,必须把控件的分页、排序属性去除并重新绑定,否则将出现 "类型“DataGridLinkButton”的控件“DataGrid1__ctl14__ctl1”必须放在具有 runat=server 的窗体标记内。"错误!
而我直接使用导致的结果是:
只能在执行Render() 的过程中调用 RegisterForEventValidation
解决方法:
1、在Web.Config文件中:在<system.web></system.web>标记中添加如下代码:
<system.web>
<pages enableEventValidation="false"> </pages>
</system.web>
2、在具体的.aspx页面的源代码中修改代码,如下:
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="GridView_Export_Excel.aspx.cs" Inherits="GridView_Export_Excel" %>
原因:
在实现"将GridView中的数据导出到Excel中"的时候出现了如下错误: 用户代码未处理 InvalidOperationException
只能在执行 Render() 的过程中调用 RegisterForEventValidation; EnableEventValidation属性是 .NET Framework 2.0 中是新增的属性,默认的情况下该属性的值为true;通过这个新增的功能ASP.NET会检查 POST方法中的所带的参数,如果认为不合法,就会抛出异常。这个设计的目的是为了防止恶意用户利用post 方法发送一些恶意数据,但是有时也会出现类似上面的错误。 只要禁止这个功能,问题就能得到解决。可以通过以下两种途径解决:
待续.......
或许你还对下面的文章感兴趣
Comments
- 1.kramon
- http://kramon.net
- 不错,不错..iambbp 于 2009-5-5 20:00:08 回复^_^见笑啦
- 2009-5-4 10:22:36 回复
