如何使用asp.net隐藏和取消隐藏Excel工作表的列

nam*_*mar 6 .net c# asp.net

我有一个需要实现的功能.

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

编辑:

我在.aspx页面上有一个gridview控件,我使用以下代码导出到excel:

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

hide在将gridview导出到excel之前,要求是某些列(在RowDataBound或类似事件中),并且unhide在Microsoft Excel中打开文件后,导出该文件的用户应该能够使用隐藏列.由于html我尝试使用网格视图重命名display:none,这是隐藏列,但我无法unhide在Microsoft Excel中使用它.

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

Aar*_*ron 11

我在工作中使用excel很多,使用EPPlus要容易得多.您可以从NuGet将其添加到您的项目中.

要使用EPPlus隐藏/取消隐藏列,您所要做的就是:

worksheet.Column(columnPosition).Hidden = true/false;
Run Code Online (Sandbox Code Playgroud)

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

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

如果你想要这个方法,我可以在下次工作时用它更新这篇文章.