一個將datagrid控制項內容輸出到excel檔案的demo.
產生EXCEL檔案#region 產生EXCEL文件
公有無效 setToExcel()
{
// Response.Clear();
// 回應.Buffer= true;
// Response.Charset="utf-8";
if (eformsn.Text=="")
{
DataGrid1.Visible=false;
Label1.Text="要匯入EXCEL,請先輸入申請單號!";
Label1.Visible=true;
}
別的
{
dl.DataSource=DB("query", "從 msi_eol_list_line select * where eformsn="+eformsn.Text+" order by eformsn").Tables[0].DefaultView;
dl.DataBind();
//下面這行很重要,附件參數表示作為附件下載,您可以改成在線在線打開
//filename=FileFlow.xls 指定輸出檔案的名稱,注意其副檔名和指定檔案類型一致,可以為:.doc .xls .txt .htm
Response.AppendHeader("Content-Disposition","attachment;filename=EOL_" +eformsn.Text+".xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
//Response.ContentType指定文件類型可以為application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他瀏覽器直接支援文檔
Response.ContentType = "應用程式/ms-excel";
dl.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//將目標資料綁定到輸入流輸出
//這個輸出表示本頁,你也可以綁定datagrid,或其他支援obj.RenderControl()屬性的控件
dl.RenderControl(oHtmlTextWriter);
//this.DataBind.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
響應.End();
}
}
#endregion