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

问题描述:

我有一个网格视图。其中包含一些列。假设它有10列,其中只有8列有标题,而2 列标题是空的。现在我将这个gridview导出到excel中,其中包含所有10列没有名称的2列。 如何在将GridView导出到excel时排除2个空头列。我使用下面的代码是一样的:如何在excel中导出网格视图时跳过一些列?

 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(); 
       } 
      } 
     } 

你可能只是不包括在你的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); 
      } 

什么代码的那部分确实通过标题行中的每个单元格是循环的,如果它是空的,不包括它。然后将其添加到HTML表格。这可以调整,如果想要的话,以便表中的其余部分添加这些列所属的单元格。如果这不是你需要的,或许你的实际Gridview有一些截图,并且期望的输出将是理想的。

祝你好运!

+0

你能举个例子吗“只是不在你的HTML表格中包含这两列” – Sandy

相反,您可以隐藏在导出使用下面的代码练成那些列

this.myGridview.Columns [0]。可见= FALSE;

其中'0'是我们要隐藏的列的索引。

+0

我和桑迪有同样的需求,我只是在使用一个使用旧版vb.net代码的DataGrid控件。 user2508258想法解决了我的问题。我的vb.net代码:DataGrid1.Columns(0).Visible = False(我想在导出到Excel期间删除第一列)。 – Doreen