与这里的一些答案类似,我通过以下方式关闭Excel文件中的网格线:
private ApplicationClass _xlApp;
. . .
_xlApp = new ApplicationClass { UserControl = true };
_xlApp.ActiveWindow.DisplayGridlines = false;
然而,在我的工作簿中,我创建了两个工作表,第二个工作表需要显示网格线。如何在工作表级别上切换显示网格线?
我尝试了以下方法:
private ApplicationClass _xlApp;
private ApplicationClass _xlApp2;
. . .
_xlApp = new ApplicationClass { UserControl = true };
_xlApp.ActiveWindow.DisplayGridlines = false;
. . .
_xlApp2 = new ApplicationClass { UserControl = true };
_xlApp2.ActiveWindow.DisplayGridlines = true;
...但是在运行时,它发出了一封电子信件,告诉我上面显示的最后一行"对象引用未设置为对象实例"。
那么我能否将一个表设置为网格线,另一个不设置,还是我必须自己处理并添加通用边框到第二个表中?
更新
David Tansey提供的链接很有趣,但它没有提供任何具体或抽象的示例来使用Worksheetview对象。所以我搜索了"c# excel interop worksheetview displaygridlines example"并找到了this。
然后我推断出这个"虚拟傻瓜"代码:
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
...并将其C#化:
// existing:
private ApplicationClass _xlApp;
_xlApp = new ApplicationClass { UserControl = true };
// new / extrapolated:
WorksheetView wsv = _xlApp.ActiveWindow.SheetViews(2);
wsv.DisplayGridlines = true;
wsv.DisplayZeros = true;
...但是却得到了编译时的错误提示,"非可调用成员 'Microsoft.Office.Interop.Excel.Window.SheetViews' 不能像方法一样使用。"
因此,我尝试了以下方法:
WorksheetView wsv = (WorksheetView)_xlApp.Sheets[2];
wsv.DisplayGridlines = true;
wsv.DisplayZeros = true;
它编译通过了,但在运行时我感到非常失望(甚至可以引用亨珀丁克的话说是“被打败”),因为出现了“无法将COM对象类型'System.__ComObject'强制转换为接口类型'Microsoft.Office.Interop.Excel.WorksheetView.'...不支持此类接口”的错误。
那么,在C#中是否有一种方法来解决这个问题,还是这是病毒比C#更擅长的领域之一?
更新2
这个变化主题的变体引起了电子精灵相同的反应:
_xlSheetDelPerf = (Worksheet)_xlSheets.Item[2];
WorksheetView wsv = (WorksheetView)_xlSheetDelPerf;
wsv.DisplayGridlines = true;
wsv.DisplayZeros = true;
WorksheetView
对象,该对象具有DisplayGridLines
属性。https://msdn.microsoft.com/zh-cn/library/office/ff837066.aspx - David TanseyWorksheetView
的转换不起作用。你对 Sheets[2] 的调用是 null 吗?它是否返回一个WorksheetView
? - The Muffin Man