[英]Exporting a gridview to excel in c#
我必須將gridview導出為excel。 我在按鈕單擊事件函數中使用以下代碼:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition","attachment;filename=sample.xls");
Response.Charset = "";
Response.ContentType = "app`enter code here`lication/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
grdVw.RenderControl(htw);
Response.Write(stringWriter.ToString());
Response.End();
當我運行此對話框時,將打開一個對話框,顯示要下載一個空XML文件。 當我嘗試調試它時,我發現網格具有數據,但未填充stringWriter。 我試圖將內容類型更改為“ application / ms-excel”等,但沒有結果。 代碼中的錯誤是什么?stringWriter無法填充的原因可能是什么?
提前致謝
我假設grdVw.RenderControl(htw);
引發一個異常,即GridView沒有以服務器形式呈現。
嘗試在調試器中執行它,我相當確定您會看到該異常。
您可以通過重寫VerifyRenderingInServerForm來避免此異常
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the specified ASP.NET
// server control at run time.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.