方法很簡單,只是將DataGrid的內容輸出到HtmlTextWriter流,再將流作為附件讓使用者下載或者用Excel開啟.
此方法雖然簡單,但能實現功能.
private void button_OutExcel_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
this.EnableViewState = false;
//定義輸入資料流
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter txtwriter = new HtmlTextWriter(writer);
//將DataGrid中的內容輸出到txtwriter流中
this.DataGrid1.RenderControl(txtwriter);
//作為附件輸出,filename=FileFlow.xls 指定輸出檔案的名稱,注意其副檔名和指定檔案類型相符,可以為:.doc .xls .txt .htm
Response.ContentType = "application/ms-excel"; //ContentType指定檔案類型 可以為application/ms-excel application/ms-word application/ms-txt application/ms-html 或其他瀏覽器可直接支援文檔
Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls"); //下載
//Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
Response.Write(writer);
Response.End();
}