using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
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
}
protected void Button1_Click(object sender, EventArgs e)
{
ExpertControl(this, DocumentType.Word);
}
}
上述代码,运行之后,只能显示文字不能正常显示图片。如果word中含有图片,则图片无法显示,图片无法显示是由于图片是相对地址,将图片改为绝对地址后,例如:图片的路径为改成站点服务器的绝对路径如:http://192.168.0.134:8003/image/tab_01.jpg可以显示。也可以将网页中的图片直接粘贴复制到word文档中,也可正常显示。
只能在执行 Re nder() 的过程中调用 RegisterForEventValidation
当在导出Execl或Word的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportWordByIO.aspx.cs" Inherits="_Default" EnableEventValidation = "false" %>