private void printexcel()
{
Response.Clear();
Response.Buffer = true;
Response.Charset = System.Text.Encoding.Unicode.WebName;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls"); //filename 可自定
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/ms-excel "; //內容型態設為Excel
DataList1.EnableViewState = false; //把ViewState給關了
System.IO.StringWriter objStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter objHtmlTextWriter = new System.Web.UI.HtmlTextWriter(objStringWriter);
DataList1.RenderControl(objHtmlTextWriter); //只想匯DataGrid也行, 把This改 你的DataGrid ID
DataList2.RenderControl(objHtmlTextWriter);
DataList3.RenderControl(objHtmlTextWriter);
DataList4.RenderControl(objHtmlTextWriter);
Response.Write(objStringWriter.ToString());
Response.End();
}
Gridview To Excel
private void printexcel(GridView gv)
{
//匯出excel檔
Response.Clear();
Response.Buffer = true;
Response.Charset = System.Text.Encoding.Unicode.WebName;// "BIG5"; //設定字集
Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls"); //filename 可自定
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/ms-excel "; //內容型態設為Excel
gv.EnableViewState = false;
System.IO.StringWriter objStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter objHtmlTextWriter = new System.Web.UI.HtmlTextWriter(objStringWriter);
gv.RenderControl(objHtmlTextWriter);
Response.Write(objStringWriter);
Response.End();
//或是這種方式
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
Context.Response.ContentType = "application/x-excel";
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
Context.Response.AddHeader("content-disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
gv.RenderControl(hw);
Context.Response.Write(tw.ToString());
Context.Response.End();
}
留言列表