2010年6月23日 星期三

DataTable 匯出excel

protected void export_excel(DataTable dt, String filename)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename= " + filename + ".xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "utf-8";
//避免文數字問題(004 => 4),強制轉文字
Response.Write(" <style>");
Response.Write("td{mso-number-format:\"\\@\";}");
Response.Write("</style>");
gv.DataSource = dt;
gv.DataBind();
gv.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}

沒有留言:

張貼留言