GridView - 在导出到Excel时删除"编辑"和"删除"列

Jos*_*ons 1 asp.net gridview export-to-excel

感谢您查看我的问题和帮助.我有一个用C#构建的asp.net应用程序.该应用程序具有简单的gridview.我有一个按钮可以将gridview导出到excel中,这也可以.但是,我的gridview在第1列中有一个编辑链接,在第2列中有一个删除按钮.如果这些列也导出为ex​​cel.如何从导出中阻止这两列?我尝试了一些事情:

GridView1.Columns.RemoveAt(0);
GridView1.Columns.RemoveAt(1);
Run Code Online (Sandbox Code Playgroud)

和...

GridView1.Column(0).visible = false;
Run Code Online (Sandbox Code Playgroud)

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

 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;

    }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Kar*_*son 5

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)