【问题标题】:GridView - Removing Edit and Delete columns while exporting to ExcelGridView - 在导出到 Excel 时删除编辑和删除列
【发布时间】:2013-12-04 19:22:48
【问题描述】:

感谢您查看我的问题并提供帮助。我有一个用 C# 构建的 asp.net 应用程序。该应用程序有一个简单的网格视图。我有一个按钮可以将 gridview 导出到 excel 中,它也可以。但是,我的 gridview 在第 1 列有一个编辑链接,在第 2 列有一个删除按钮。如果这些列也导出到 excel。如何阻止这两列导出?我尝试了一些方法:

GridView1.Columns.RemoveAt(0);
GridView1.Columns.RemoveAt(1);

还有……

GridView1.Column(0).visible = false;

我在每次尝试后都进行了数据绑定,但它根本不起作用。我将在下面发布我的代码,也许有人可以帮助我!谢谢!

 public void ExportGridToExcel(GridView grdGridView, string fileName)
            {


            Response.Clear();
            Response.AddHeader("content-disposition",
            string.Format("attachment;filename={0}.xls", fileName));
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";

            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            grdGridView.RenderControl(htmlWrite);
            GridView1.Columns.RemoveAt(0);
            Response.Write(stringWrite.ToString());
            Response.End();

            GridView1.AllowPaging = false;

    }

girdview 的编辑功能设置为 true,删除按钮是一个模板字段,如下所示:

<Columns>
            <asp:TemplateField>
            <ItemTemplate>
            <asp:Button ID="btnDelete" CommandName="Delete" runat="server"     Text="Delete" CssClass="okbutton" OnClientClick="return confirm('Are you sure you want to delete this entry?');" />
            </ItemTemplate>
            </asp:TemplateField>

【问题讨论】:

标签: asp.net gridview export-to-excel


【解决方案1】:

您需要隐藏标题和数据行中的各个单元格,如下所示:

// Hides the first column in the grid (zero-based index)
GridView1.HeaderRow.Cells[0].Visible = false;

// Loop through the rows and hide the cell in the first column
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
    GridViewRow row = GridView1.Rows[i];
    row.Cells[0].Visible = false;
}

【讨论】:

    【解决方案2】:
    GridView1.Columns[6].Visible = false;
    

    【讨论】:

    • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of howwhy 这解决了问题。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    【解决方案3】:

    对于列:

    GridName.Columns[index].Visible = false;
    

    对于行:

    Gridname.Rows[index].Visible = false;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多