如何在excel中导出网格视图时跳过某些列?

San*_*ndy 5 asp.net gridview c#-4.0

我有一个网格视图.其中包含一些列.假设它有10列,只有8列有标题而2 列标题为空.现在我将此gridview导出到excel,其中包含所有10列,其中2列没有名称.如何在将GridView导出到excel时排除这2个空标题列.我使用以下代码:

        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            Export("Customers.xls", this.gdvMessages);
        }

        private void Export(string fileName, GridView gv)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();

                    //  add the header row to the table
                    if (gv.HeaderRow != null)
                    {
                        PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Han*_*año 3

如果您不需要这两列,则可以不在 HTML 表中包含它们......或者您可以在用户按下“导出到 Excel”按钮时重写该表而不包含这些列。您还可以将该表加上另一个带有隐藏列的表,并在用户单击“导出到 Excel”按钮时从中获取数据。此外,您根本无法显示数据,并且当用户加载页面或单击按钮时下载不带列的数据。祝你好运!

编辑:对于这个独特的场景,您可能需要按以下方式编辑代码:

 //  add the header row to the table
            if (gv.HeaderRow != null)
            {
                TableRow tr = new TableRow();

                foreach (DataControlFieldHeaderCell c in gv.HeaderRow.Cells)
                {
                    if (c.Text != " ") {
                        tr.Cells.Add(new TableCell() { Text = c.Text});
                    }
                }

                PrepareControlForExport(tr);
                table.Rows.Add(tr);
            }
Run Code Online (Sandbox Code Playgroud)

这部分代码的作用是循环遍历标题行中的每个单元格,如果它为空,则不包含它。然后将其添加到 html 表中。如果需要,可以对此进行调整,以便表格的其余部分添加这些列所属的单元格范围。如果这不是您所需要的,那么您实际的 Gridview 的一些屏幕截图和所需的输出可能是理想的选择。

祝你好运!