【问题标题】:Export multiple gridviews to multiple excel sheets将多个网格视图导出到多个 Excel 工作表
【发布时间】:2015-08-10 08:45:20
【问题描述】:

我的网站中有 3 个网格视图需要导出到 excel,但我需要每个网格视图出现在不同的工作表中。

此链接 Export GridView to multiple Excel sheet 使用非常相似的东西 Export multiple gridviews to multiple excel tabs (sheets)

为了将多个网格视图导出到多个工作表,我使用的是 .NET,并且我已经下载了 ClosedXMLDocumentFormat.OpenXml.dll

在 Web 应用程序中我没有错误,但 XLS 输出为空。

有人知道我该如何解决这个问题吗?

你能推荐其他方法吗?

提前谢谢你。

请检查下面的代码。

protected void btnExportBoth_Click(object sender, EventArgs e)
{
    XLWorkbook wb = new XLWorkbook();
    GridView[] gvExcel = new GridView[] { gv1, gv2, gv3 };

    string[] name = new string[] { "gv1", "gv2", "gv3" };

    for (int i = 0; i < gvExcel.Length; i++)
    {
        if (gvExcel[i].Visible)
        {
            gvExcel[i].AllowPaging = false;
            gvExcel[i].DataBind();

            DataTable dt = new DataTable(name[i].ToString());
            for (int z = 0; z < gvExcel[i].Columns.Count; z++)
            {
                dt.Columns.Add(gvExcel[i].Columns[z].HeaderText);
            }

            foreach (GridViewRow row in gvExcel[i].Rows)
            {
                dt.Rows.Add();
                for (int c = 0; c < row.Cells.Count; c++)
                {
                    dt.Rows[dt.Rows.Count - 1][c] = row.Cells[c].Text;
                }
            }

            wb.Worksheets.Add(dt);
            gvExcel[i].AllowPaging = true;
        }
    }

    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=Workbook_Name.xlsx");

    using (MemoryStream MyMemoryStream = new MemoryStream())
    {
        wb.SaveAs(MyMemoryStream);
        MyMemoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}

【问题讨论】:

  • 可能是您的 gridview 不包含任何数据,因为我看不到您为 gridviews 指定数据源。

标签: c# asp.net excel gridview


【解决方案1】:

您确定在btnExportBoth_Click 方法上填充了gridview 吗?

        gvExcel[i].AllowPaging = false;
        gvExcel[i].DataBind();

btnExportBoth_Click 方法中,您必须调用该方法才能像在网络上一样填充gridview。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2023-03-21
    相关资源
    最近更新 更多