ASP.NET中GridView數據導出到Excel


/// <summary>
/// 導出按鈕
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExport_Click1(object sender, EventArgs e)
{
    this.gv.AllowPaging = false;
    this.gv.AllowSorting = false;
    Query();//獲取數據並綁定到GridView

    toExcel(this.gv);

    this.gv.AllowPaging = true;
    this.gv.AllowSorting = true;
    Query();//獲取數據並綁定到GridView
}
/// <summary>
/// 導出到Excel
/// </summary>
/// <param name="gv"></param>
void toExcel(GridView gv){
    Response.Charset = "GB2312";
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

    string fileName = "export.xls";
    string style = @"<style> .text { mso-number-format:\@; } </script> ";
    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
    Response.ContentType = "application/excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    this.gv.RenderControl(htw);
    Response.Write(style);
    Response.Write(sw.ToString());
    Response.End();
}
/// <summary>
/// 這個重寫貌似是必須的
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control) { }
 

備注:

1、gv就是頁面上的GridView空間名稱;

2、代碼中的Query方法所做的是,獲取數據並綁定到GridView。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM