在Excel工作表中保存自定义属性

我们在C#中有Excel加载项。 为了支持一些function,我们使用Worksheet.CustomProperties 。 我们发现,添加一些自定义属性后,我们正在改变它的价值。 比如我们通过Add方法设置“1”。 在某个时刻,我们将相同的值更改为“2”。 然后我们保存工作簿并再次打开。 出于某种原因,我们看到“1”而不是“2”。 为什么? 看起来我错过了什么,但不知道是什么。 更新:

public class CustomPropertyUtil { protected readonly Worksheet Sheet; public WorkSheetCustomPropertyUtil(Worksheet sheet) { this.Sheet = sheet; } protected bool Exists(string propertyName) { try { return Sheet.CustomProperties.Cast<CustomProperty>().Any(c => c.Name == propertyName); } catch (System.Runtime.InteropServices.COMException) { return false; } } protected object GetValue(string propertyName) { CustomProperty property = GetProperty(propertyName); return property != null ? property.Value : null; } protected void SetValue(string propertyName, object value) { CustomProperty customProperty = GetProperty(propertyName); if (customProperty == null) { AddCustomProperty(propertyName, value); } else { customProperty.Value = value; } } private void AddCustomProperty(string propertyName, object value) { Sheet.CustomProperties.Add(propertyName, value); } protected CustomProperty GetProperty(string propertyName) { return Exists(propertyName) ? Sheet.CustomProperties.Cast<CustomProperty>().FirstOrDefault(c => c.Name == propertyName) : null; } } 

这是我们如何pipe理自定义属性。 当我们保存时我们做以下事情:

 Workbook.SaveAs(filePath, AccessMode: XlSaveAsAccessMode.xlNoChange); 

当我打开它在VBA中,我看到我的CustomProperties没有保存。

也许我已经简化了你的任务,但是我设置了自定义属性(例如,文件保存到Sharepoint文档库时的属性),如下所示:

 Excel.Workbook wb; wb.ContentTypeProperties["Region"].Value = "Northeast"; 

有可能这些属性与你正在谈论的属性不同……这将改变属性,例如,当你点击“文件”选项卡并在最右边的面板中看到“属性”列表。