底下說明在 ASP.NET 匯出頁面內容到 Excel 或 Word 的步驟 如果要將整個頁面匯出
需在 .aspx 的 Page 指示詞中加入 EnableEventValidation=“false”
範例如下:
<%@ Page Language="C#" AutoEventWireup="true"匯出 Excel 或 Word 的程式碼如下:
CodeFile="UseCase4.aspx.cs" Inherits="UseCase4" Debug="true"
EnableEventValidation="false"%>
protected void btnExportExcel_Click(object sender, EventArgs e)若只匯出某個 Control(例如:GridView1) 時, 需 override VerifyRenderingInServerForm(), 裡頭不必寫任何的程式碼。
{
//匯出 Excel 或 Word
string fileName = "UseCase4.xls"; //excel
//string fileName = "UseCase4.doc"; //word
Response.Clear();
//指定下載的檔名
Response.AddHeader("content-disposition",
"attachment;filename=" + fileName );
Response.ContentType = "application/vnd.ms-excel"; //excel
//Response.ContentType = "application/vnd.ms-word"; //word
//加入下面兩行才可正常顯示中文
Response.Write("<head><meta http-equiv=Content-Type content=text/html;" +
"charset=big5></head>");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("big5");
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
this.RenderControl(htw);
//若要只匯出 GridView1, 請將 this 改為 GridView1
Response.Write(sw.ToString());
Response.End();
}
範例如下:
public override void VerifyRenderingInServerForm(Control control)參考連結:
{
}
沒有留言:
張貼留言