使用 EPPlus 将 Gridview 导出到 ASP.net 中的 Excel

Export Gridview to Excel in ASP.net with EPPlus

我正在尝试将数据从我的 gridview 导出到 Excel 文件。

我试过使用 EPPlus 库,但即使我在算法开始时禁用分页,它也只打印 gridview 的第一页。

这是使用 EPPlus 的代码:

Response.Clear();
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridData.xlsx");

cgvReferentiel.AllowPaging = false;    // here I'm disabling paging

if (cgvReferentiel.Rows.Count > 0)
{
    var dtb = new DataTable();

    // Creating table headers
    dtb.Columns.Add("PAYS", typeof(string));
    dtb.Columns.Add("SOCIETE", typeof(string));
    dtb.Columns.Add("SECTION", typeof(string));
    dtb.Columns.Add("MATRICULE", typeof(string));
    dtb.Columns.Add("NOM(S)", typeof(string));
    dtb.Columns.Add("PRENOM(S)", typeof(string));
    dtb.Columns.Add("IDENTIFIANT", typeof(string));
    dtb.Columns.Add("SOURCE", typeof(string));
    dtb.Columns.Add("TYPE", typeof(string));
    dtb.Columns.Add("DATE D'ARCHIVAGE", typeof(string));

    // Adding rows content
    foreach (GridViewRow row in cgvReferentiel.Rows)
    {
        var pays = row.Cells[0].Text;
        var societe = row.Cells[1].Text;
        var section = row.Cells[2].Text;
        var matricule = row.Cells[3].Text;
        var nom = row.Cells[4].Text;
        var prenom = row.Cells[5].Text;
        var identifiant = row.Cells[6].Text;
        var source = row.Cells[7].Text;
        var type = row.Cells[8].Text;
        var date = row.Cells[9].Text;

        dtb.Rows.Add(pays, societe, section, matricule, nom, prenom, identifiant, source, type, date);
    }

    // Writing the excel file
    using (ExcelPackage pck = new ExcelPackage())
    {
        ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Historique");
        wsDt.Cells["A1"].LoadFromDataTable(dtb, true, TableStyles.Light20);
        wsDt.Cells.AutoFitColumns();

        Response.BinaryWrite(pck.GetAsByteArray());
    }

    Response.Flush();
    Response.End();
}

这段代码有什么问题?

我知道是怎么回事了。我需要在禁用分页后绑定 gridview 行:

cgvReferentiel.DataBind();