星期五, 10月 09, 2009

.net 輸出 Excel 的報表

今天在輸出 excel 報表..發現怎麼輸出中文都變成亂碼..網路上找了一堆資料..零零碎碎的東湊西湊的..終於解決問題..這裡紀錄一下..以後有需要的人可以輕鬆解決這個問題..看 code 吧..

protected void Page_Load(object sender, EventArgs e)
{
string encoding = "utf-8";
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=Report.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding(encoding);
Response.Charset = encoding;

using (DataClassesDataContext db = new DataClassesDataContext())
{
GridView1.DataSource = db.訂貨主檔s.Take(10);
GridView1.DataBind();
}

StreamWriter sw = new StreamWriter(
Response.OutputStream, System.Text.Encoding.GetEncoding(encoding));
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
GridView1.RenderControl(hw);
sw.Write(tw.ToString());
sw.Flush();
Response.End();
}

不過上面的code會產生一個錯誤..如下..

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

這意思是說..我必需要把 gridview 這個 control 這放在 form 裡面..由於我要產生 Excel 報表..當然會有問題..所以要把 Page 檢查 control 是不是有在 form 那個 method 覆寫掉才行..

public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}

解決..收工..

參考:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.page.verifyrenderinginserverform%28VS.80%29.aspx
http://www.w3schools.com/media/media_mimeref.asp
http://msdn.microsoft.com/en-us/library/ms525405.aspx

沒有留言: