{
//呼叫的片段、方式
// export_excel(要匯出的 Gridview 名稱, 匯出的檔名,模式); // 1=會加入日期時間
export_excel("gridview1", "output",1);
}
private void export_excel(string gvname, string filename, int t_mode)
{
// 呼叫方式 export_excel("gridview1", "output",1);
// export_excel(要匯出的 Gridview 名稱, 匯出的檔名,模式); // 1=會加入日期時間
GridView xgv = (GridView) FindControl(gvname);//重點可增加數入excel
string style = "<style> .text { mso-number-format:\\@; } </script> ";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
Response.Clear();
if(t_mode==1) // 加上時間日期
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "_" + DateTime.Now .ToString ("yyyyMMdd-HHmm") + ".xls");
else
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename +".xls");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
xgv.RenderControl(hw);//重點可增加數入excel
Response.Write(style);
Response.Write(sw.ToString().Replace("<div>", "").Replace("</div>", ""));
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
}
參考網址:http://blog.xuite.net/tolarku/blog/26786484-ASP.NET+%E7%B0%A1%E5%96%AE%E4%BA%94%E6%AD%A5%E9%A9%9F%E5%B0%87+GridView+%E8%B3%87%E6%96%99%E8%BD%89%E6%AA%94%E5%88%B0+Excel
沒有留言:
張貼留言