[英]ASP.NET Gridview to excel
我有一個帶有Gridview
的頁面,當單擊按鈕時,我應該將數據從Gridview
導出到.xls
文件。 我已經嘗試了很多方法。 這是我的代碼:
protected void export_Click(object sender, EventArgs e)
{
Response.ClearContent();
//Response.Buffer = true;
//Response.ClearHeaders();
//Response.CacheControl = "no-cache";
//Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Content-Disposion","attachment; filename=Clients.xls");
Response.ContentType = "application/excel";
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
grid.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
問題是當我單擊按鈕時,它正在導出aspx
文件。 我已經嘗試了Stackoverflow中的所有答案以及其他來源的答案。 但是,我無法糾正它。 我需要確切的理由以及可能的解決方案。(我也嘗試將Content-type
為"application/excel"
, "application/vn"
, "application/vn-excel"
。)
您只需遵循以下代碼,即可正常工作。
protected void cmdExport_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls"); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter WriteItem = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem); GridView1.AllowPaging = false; DataTable dtSupplier = (DataTable)ViewState["dtSupplier"]; GridView1.DataSource = dtSupplier; GridView1.DataBind(); GridView1.RenderControl(htmlText); Response.Write(WriteItem.ToString()); Response.End(); }
希望這會幫助你。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.