2013-07-03 86 views
3

我有一个需要实现的功能。如何使用asp.net隐藏和取消隐藏excel工作表的列

我们将网格数据绑定到excel导出,并且工作正常。 但我得到了新的要求,我必须隐藏Excel导出中的列。 之后,当用户打开excel工作表时,他应该可以选择隐藏通过代码隐藏的列。

编辑:

我有我的.aspx页面上的GridView控件其中我出口使用下面的代码,以擅长:

public static void Export(string filename, GridView grid) 
    { 

      HttpContext.Current.Response.Clear(); 
      HttpContext.Current.Response.Buffer = true; 
HttpContext.Current.Response.AddHeader("content-disposition", 
      string.Format("attachment; filename={0}", filename.Replace(" ", "") + ".xls")); 
      HttpContext.Current.Response.Charset = ""; 
      HttpContext.Current.Response.ContentType = "application/vnd.xls"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 
      grid.HeaderStyle.BackColor = System.Drawing.Color.Cyan; 
      GridViewRow row = new GridViewRow(0, 1, DataControlRowType.DataRow, DataControlRowState.Normal); 
      TableCell cell = new TableCell(); 
      cell.Text = String.Format("{0}", Heading[count]); 
      cell.ColumnSpan = grid.Rows[1].Cells.Count; 
      cell.Attributes.Add("style", "background-color: white; color: black;text-align:left;"); 
      cell.Attributes.Add("class", "yellow"); 
      row.Cells.Add(cell); 
      grid.Controls[0].Controls.AddAt(0, row); 
      grid.RenderControl(htw); 
      DataTable dt = new DataTable(); 
      DataRow dr; 
      dt.Columns.Add(new System.Data.DataColumn(" ", typeof(String))); 
      dr = dt.NewRow(); 
      dr[0] = " "; 
      dt.Rows.Add(dr); 
      GridView gvSpace = new GridView(); 
      gvSpace.DataSource = dt; 
      gvSpace.GridLines = 0; 
      gvSpace.DataBind(); 
      gvSpace.RenderControl(htw); 
      grid.HeaderStyle.BackColor = System.Drawing.Color.Cyan; 
      HttpContext.Current.Response.Write(@"<style> .sborder { color : Black;border : 1px Solid Black; } .yellow {background-color:yellow;color:black;} </style> "); 
      HttpContext.Current.Response.Write(sw.ToString()); 
      HttpContext.Current.Response.End(); 
      HttpContext.Current.Response.Flush(); 
    } 

的要求是hide一些列(在的RowDataBound或类似事件),然后将gridview导出为ex​​cel,导出该文件的用户应该能够在Microsoft Excel中打开该文件后隐藏列unhide。由于网格视图被重新编号为html我曾尝试使用display:none,这是隐藏列,但我不能在它在Microsoft Excel中。

那么如何隐藏网格视图列,然后将其导出到excel并在我在Microsoft Excel中打开文件时取消隐藏列?

+0

@JeremyThompson他希望它在ASP.NET代码中 – logixologist

回答

6

我在工作中使用excel很多,使用EPPlus更容易。您可以将它添加到NuGet的项目中。

所有你必须为了隐藏/显示用EPPlus列做的是:

worksheet.Column(columnPosition).Hidden = true/false; 

其中columnPosition是要隐藏的列的索引。

我在工作中编写了一个方法,它将gridview作为一个peram并将其转换为数据表。您可以在onrowdatabound事件中隐藏gridview列,并将gridview传递给该方法。然后,您可以使用EPPlus生成Excel文件,并根据需要取消隐藏列(可能已经取消隐藏)。

如果你想要的方法,我可以更新这个职位,下次我在工作。

3

使用此。

的行

worksheet_sub.Row(i).Height = 0; 

为列

worksheet_sub.Column(i).Width= 0; 

这里i

1

如果你想隐藏多个列列的索引或行号:

var targetColumns = 5; // Some value for the cumber of columns you want to hide 
for (int i = 1; i < targetColumns ; i++) 
{ 
    yourWorksheet.Column(i).Hidden = true; 
} 
相关问题