Question

I have a project that has two requirements. One is to create a simple program that adds a custom property to an excel spreadsheet from outside of Excel. The second requirement is to search for, and, if found, extract that custom property from within an application level vsto Excel add-in.

So far I have met the first requirement and have a program that adds some data to the CustomFileProperties of a workbook via OpenXML as follows:

using (var wb = SpreadsheetDocument.Open(WorkbookToRegister, true))
{
    Log("Finding existing properties...");
    var customPropsPart = wb.CustomFilePropertiesPart;
    if (customPropsPart == null)
    {
        Log("No properties found, adding new part...");
        customPropsPart = wb.AddCustomFilePropertiesPart();
    }

    var props = customPropsPart.Properties;
    if (props == null)
    {
        props = new DocumentFormat.OpenXml.CustomProperties.Properties();
        customPropsPart.Properties = props;
    }

    foreach (var prop in props.Where(
        prop => ((CustomDocumentProperty)prop).Name.Value == "niuVersionNumber"))
    {
        Log("Removing existing properties...");
        prop.Remove();
    }

    Log("Adding new properties,..");
    var versionProp = new CustomDocumentProperty();
    versionProp.FormatId = Guid.NewGuid().ToString("B");
    propertyGuid = versionProp.FormatId;
    versionProp.Name = "niuVersionNumber";
    propertyName = versionProp.Name;
    versionProp.VTBString = new VTBString(versionNumber);
    props.AppendChild(versionProp);
    var pid = 2;

    Log("Assigning IDs to properties,..");
    foreach (var item in props.Cast<CustomDocumentProperty>())
    {
        item.PropertyId = pid++;
    }
    Log("Saving...");
    props.Save();
}

As you can see, the code adds to the file a property named "niuVersionNumber" with a value of versionNumber. This works flawlessly.

The problem is the second requirement. I haven't been able to figure out how to access that custom property from within the VSTO API.

I've searched MSDN and the interwebs, and am aware of the OpenXML and VSTO API documentation, but am having difficulty fully understanding how to get this to work.

Any suggestions or examples would be appreciated!

Regards,

Joe

Was it helpful?

Solution

Thanks for your feedback, but in the end the problem was that I was targeting the wrong object. I missunderstood the difference between custom properties and custom xml parts.

Rather than targeting the document's custom properties object like so:

props = new DocumentFormat.OpenXml.CustomProperties.Properties();

I should have been targetting the document's custom xml parts like so:

var customWorkBookVersionXmlPart = wb.WorkbookPart.AddCustomXmlPart("application/xml");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top