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" %>