2013-07-03 129 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; 
} 
相關問題