Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide an excel column?

Tags:

c#

excel

com


I need to hide an excel column entirely. I used the below code but didn't work:

public void Hide (params string[] columns)
{
    foreach(var column in columns)
    {
        Range range = (Range) oSheet.Columns[column, Type.Missing];
        range.EntireColumn.Hidden = true;
    }
}

What am I missing?

like image 458
Galilyou Avatar asked Jan 11 '12 19:01

Galilyou


People also ask

How do you unhide hide columns in Excel?

On the Home tab, in the Cells group, click Format. Do one of the following: Under Visibility, click Hide & Unhide, and then click Unhide Rows or Unhide Columns.

How do I hide columns in Excel without right clicking?

Hide Columns in Excel Using a Keyboard ShortcutPress and hold down the Ctrl key on the keyboard. Press and release the 0 key without releasing the Ctrl key. The column containing the active cell should be hidden from view.


1 Answers

It turns out that hiding a span of rows and columns you specify couldn't be a heck of a lot easier. Here's how you do it, in two easy steps:

1) Name your worksheet:

private Worksheet _xlSheet;

2) Now, name a range, including the first row and column to hide and then the last row and column to hide, like so:

var hiddenRange = yourWorksheet.Range[_xlSheet.Cells[42, 1], _xlSheet.Cells[999, 13]];
hiddenRange.EntireRow.Hidden = true;

This assumes the first row you want to hide is 42, etc. Obviously you will want to change these hardcoded values.

As an example, here's some actual code, using constants and variables instead of hardcoded vals, which responds to a boolean whose value indicates whether the range should be hidden or not:

private bool _hide;
private int _curTopRow;
private static readonly int ITEMDESC_COL = 1;
private static readonly int TOTALS_COL = 16;
. . .
if (_hide)
{
    var hiddenRange = _xlSheet.Range[_xlSheet.Cells[_curTopRow, ITEMDESC_COL], _xlSheet.Cells[_curTopRow+3, TOTALS_COL]];
    hiddenRange.EntireRow.Hidden = true;
}

Note that you need to reference the Microsoft.Office.Interop.Excel assembly.

like image 189
B. Clay Shannon-B. Crow Raven Avatar answered Sep 18 '22 08:09

B. Clay Shannon-B. Crow Raven