gridview導(dǎo)出excel數(shù)據(jù)如何去掉篩選

小億
87
2023-11-07 12:38:46

要去掉 GridView 導(dǎo)出的 Excel 中的篩選,可以在導(dǎo)出之前先移除 GridView 中的篩選功能。

首先,你需要在 ASPX 頁(yè)面的 GridView 控件中設(shè)置 AllowFilteringByColumn="false",這將禁用 GridView 中的篩選功能。

<asp:GridView ID="GridView1" runat="server" AllowFilteringByColumn="false">
    <!-- GridView 的列定義 -->
</asp:GridView>

然后,在導(dǎo)出 Excel 的代碼中,使用 GridView 的數(shù)據(jù)源(比如 DataTable)來(lái)生成 Excel 文件。這樣,由于 GridView 中已經(jīng)禁用了篩選功能,導(dǎo)出的 Excel 文件中就不會(huì)包含篩選。

protected void ExportToExcel()
{
    // 獲取 GridView 的數(shù)據(jù)源
    DataTable dt = (DataTable)GridView1.DataSource;

    // 創(chuàng)建 Excel 對(duì)象
    ExcelPackage excel = new ExcelPackage();
    var worksheet = excel.Workbook.Worksheets.Add("Sheet1");

    // 將 GridView 的數(shù)據(jù)導(dǎo)出到 Excel 中
    int rowIndex = 1;
    foreach (DataRow row in dt.Rows)
    {
        int colIndex = 1;
        foreach (var cellValue in row.ItemArray)
        {
            worksheet.Cells[rowIndex, colIndex].Value = cellValue;
            colIndex++;
        }
        rowIndex++;
    }

    // 導(dǎo)出 Excel 文件
    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx");
    Response.BinaryWrite(excel.GetAsByteArray());
    Response.End();
}

以上代碼中的 ExcelFileName.xlsx 是導(dǎo)出的 Excel 文件名,你可以根據(jù)需要進(jìn)行修改。

0