Similar to some of the answers here, I turn gridlines in my Excel file off this way:
private ApplicationClass _xlApp;
. . .
_xlApp = new ApplicationClass { UserControl = true };
_xlApp.ActiveWindow.DisplayGridlines = false;
However, in my workbook, I create two sheets, and the second one needs to display gridlines. How can I toggle the displaying of gridlines at the Worksheet level?
I tried this:
private ApplicationClass _xlApp;
private ApplicationClass _xlApp2;
. . .
_xlApp = new ApplicationClass { UserControl = true };
_xlApp.ActiveWindow.DisplayGridlines = false;
. . .
_xlApp2 = new ApplicationClass { UserControl = true };
_xlApp2.ActiveWindow.DisplayGridlines = true;
...but that emitted an electronic epistle informing me at runtime that "Object reference not set to an instance of an object" on the last line displayed above.
So can I set one sheet to gridlined and the other ungridlined, or will I have to take matters into my own mitts and add universal borders to the second sheet?
UPDATE
The link from David Tansey was intiguing, but it didn't provide any concrete - or even abstract - example of how to use the Worksheetview object. So I binged (bang?) "c# excel interop worksheetview displaygridlines example" and found this.
I then extrapolated this "Virtual Buffoonery" code:
Dim wsv As WorksheetView
Set wsv = wnd.SheetViews(1)
' Display formulas and zeros, but hide
' gridlines, headings, and outlines:
wsv.DisplayFormulas = True
wsv.DisplayGridlines = False
wsv.DisplayHeadings = False
wsv.DisplayOutline = False
wsv.DisplayZeros = True
...and C#ified it thus:
// existing:
private ApplicationClass _xlApp;
_xlApp = new ApplicationClass { UserControl = true };
// new / extrapolated:
WorksheetView wsv = _xlApp.ActiveWindow.SheetViews(2);
wsv.DisplayGridlines = true;
wsv.DisplayZeros = true;
...but got the compile-time fingerwag, "Non-invocable member 'Microsoft.Office.Interop.Excel.Window.SheetViews' cannot be used like a method."
So, I tried this:
WorksheetView wsv = (WorksheetView)_xlApp.Sheets[2];
wsv.DisplayGridlines = true;
wsv.DisplayZeros = true;
It compiled, but at runtime I'm sorely disappointed (and even put out, to quote Humperdinck) by "Unable to cast COM object type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.WorksheetView.'...No such interface supported"
So is there a way to do this in C#, or is this one of those areas where Virus Bits has it over C#?
UPDATE 2
This variation on the theme elicits the same response from the electronic spirits:
_xlSheetDelPerf = (Worksheet)_xlSheets.Item[2];
WorksheetView wsv = (WorksheetView)_xlSheetDelPerf;
wsv.DisplayGridlines = true;
wsv.DisplayZeros = true;