How to hide an Excel column?


I need to hide the excel column completely. I used the code below, but did not 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?

+6
source share
2 answers

The above snippet works .. sorry guys! The problem was that my colleague-colleague used the automatic installation of all columns immediately before saving the file, which would override my settings above. Yes, a function called CloseFile() that performs two tasks, formats and then saves .. a lot of responsibilities, CloseFile() ??

+2
source

It turns out that hiding the range of rows and columns that you specified could not be much easier. Here, how you do it, in two simple steps:

1) What is your worksheet:

 private Worksheet _xlSheet; 

2) Now name the range, including the first row and column to hide, and then the last row and column to hide, for example:

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

It is assumed that the first line you want to hide is 42, etc. Obviously, you will want to change these hard-coded values.

As an example, here is some actual code that uses constants and variables instead of hard-coded vals that respond to a boolean whose value indicates whether this 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 assembly Microsoft.Office.Interop.Excel.

+2
source

Source: https://habr.com/ru/post/905747/


All Articles