如何在Excel工作簿中存储信息

时间:2009-07-01 07:22:34

标签: excel persistence vsto add-in

我正在使用VS2008和VSTO(C#)在Office 2007上编写Excel Addin。 当用户再次使用此类信息打开工作簿时,此插件需要存储嵌入或工作簿内部的信息以恢复某些状态。在保存工作簿之前,Addin在XML中序列化了所有信息,在打开WorkBook之后,Addin尝试在发现它时反序列化这些信息。

我尝试使用 Office.DocumentProperties ,但每个字符串元素都被截断(最多256个字符)

在活动 Excel.AppEvents_WorkbookOpenEventHandler Excel.AppEvents_WorkbookBeforeCloseEventHandler

Office.DocumentProperties properties = (Office.DocumentProperties)this.Application.ActiveWorkbook.CustomDocumentProperties;
properties.Add(Constants.ADDIN_PERSISTENCE, false, Office.MsoDocProperties.msoPropertyTypeString, serialize(configurationInstance), null);

在活动 AppEvents_WorkbookOpenEventHandler

Office.DocumentProperties properties = (Office.DocumentProperties)Application.ActiveWorkbook.CustomDocumentProperties;
Configuration configurationInstance = deserialize((string)properties[Constants.ADDIN_PERSISTENCE]);

但这不起作用,因为序列化返回的字符串长于256个字符。

在其他Addin中,在Excel 2003上,我将信息存储在第一个单元格中的“非常隐藏”的工作表上,并带有一个奇怪的名称。我不知道是否有更好的解决方案。

1 个答案:

答案 0 :(得分:4)

好的,我找到了“好方法”。 Office.CustomXMLParts是用于存储XML数据的集合。

您可以直接在Msdn 1

找到相关信息

MSDN示例:

private void AddCustomXmlPartToWorkbook(Excel.Workbook workbook){
string xmlString =
    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
    "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
        "<employee>" +
            "<name>Karina Leal</name>" +
            "<hireDate>1999-04-01</hireDate>" +
            "<title>Manager</title>" +
        "</employee>" +
    "</employees>";
Office.CustomXMLPart employeeXMLPart = workbook.CustomXMLParts.Add(xmlString, missing);
}