Gridview 匯出成EXCEL
1. 於Page中加入 EnableEventValidation = "false"
2.於Button Click 中加入
string filename = "filename";
GridView xgv = (GridView)FindControl("GridViewName");
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();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "_" + DateTime.Now.ToString("yyyyMMdd-HHmm") + ".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);
Response.Write(style);
Response.Write(sw.ToString().Replace("<div>", "").Replace("</div>", ""));
Response.End();
3. 加入
public override void VerifyRenderingInServerForm(Control control)
{
}
不然會有Runat Server 的ERROR
4.因避免Excel 會自動轉換格式,故以文字格式輸出
於RowDataBound 中加入
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Attributes.Add("class", "text");
e.Row.Cells[3].Attributes.Add("class", "text");
}
}
留言列表