将string或数值存储在Excel工作表对象属性中

我的意图是在工作表对象属性中存储一个string/数字值,这对用户来说应该是不可读写的。

我已经尝试像下面,但得到例外。

Excel.Worksheet ws = Globals.ThisWorkbook.Application.ActiveWorkbook.ActiveSheet; ws._CodeName = "abc"; 

是否有可能将自定义值存储在工作表对象中

虽然你的代码是c#你也会显示一个VBA标签,所以这里是一个VBA例程来添加一个自定义属性到工作表中:

 Option Explicit Sub foo() Dim WS As Worksheet Dim sCPName As String Dim sCPValue As String Dim I As Long Set WS = Worksheets("sheet1") sCPName = "Request ID" sCPValue = 12345 With WS.CustomProperties For I = 1 To .Count If .Item(I).Name = sCPName Then Exit For Next I If I > .Count Then .Add sCPName, sCPValue Else .Item(I).Value = sCPValue End If End With End Sub 

ws._CodeName是一个ReadOnly属性( MSDN参考 )。 因此,你只能阅读它,而不能覆盖它。

但是,如果要更改工作表的名称,则可能是这种情况:

 using System; using Excel = Microsoft.Office.Interop.Excel; class Startup { static void Main() { Excel.Application excelApp = new Excel.Application(); Excel.Workbook wkbReport = Open(excelApp, @"C:\Testing.xlsx"); Excel.Worksheet ws = wkbReport.Worksheets[1]; Console.WriteLine(ws._CodeName); ws.Name = "ABC"; Console.WriteLine("END"); excelApp.Visible = true; } public static Excel.Workbook Open(Excel.Application excelInstance, string fileName, bool readOnly = false, bool editable = true, bool updateLinks = true) { Excel.Workbook book = excelInstance.Workbooks.Open( fileName, updateLinks, readOnly, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); return book; } } 

这是这样的:

在这里输入图像说明