c#.net 資料轉出Excel
protected void btnExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");//防中文亂碼
Response.AddHeader("content-disposition", "attachment;filename=xxx.xls");//excel檔名
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
sqlExcel.SelectCommand = @"Select * From dbBase;";//(sqlExcel:頁面上的物件 [asp:SqlDataSource])來源的Select
gv.DataSource = this.sqlExcel.Select(DataSourceSelectArguments.Empty);
gv.ShowHeader = true;
gv.DataBind();
gv.RowStyle.HorizontalAlign = HorizontalAlign.Center;
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}