Named Ranges in Excel OpenXML

aaron picture aaron · Sep 2, 2011 · Viewed 8.3k times · Source

I am trying to create named ranges in Excel with OpenXML. I am able to add a DefinedName in the DefinedNames collection, but that does not seem to do anything. I noticed a place in the ExtendedFileProperties where the names of ranges are being saved, a structure called "TitlesOfParts". I have tried adding an entry in there but that causes excel to throw an error and the named range is not created. Here is the code I am using:

public void AddNamedRange(string pNamedRangeRef, string pNamedRangeName)
    {
        DefinedName _definedName = new DefinedName() { Name = pNamedRangeName, Text = pNamedRangeRef };
        _workbook.Descendants<DocumentFormat.OpenXml.Spreadsheet.DefinedNames>().First().Append(_definedName);
        DocumentFormat.OpenXml.VariantTypes.VTLPSTR _t = new DocumentFormat.OpenXml.VariantTypes.VTLPSTR() { Text = pNamedRangeName };
        _spreadsheet.ExtendedFilePropertiesPart.Properties.TitlesOfParts.VTVector.Append(_t);
        _spreadsheet.ExtendedFilePropertiesPart.Properties.TitlesOfParts.VTVector.Size++;
    }

Answer

jklemmack picture jklemmack · Jan 16, 2012

Using the Open XML SDK 2.0 Productivity Tool for Microsoft Office, to define a global/workbook-wide named range is pretty easy:

DefinedNames definedNamesCol = new DefinedNames();    //Create the collection
DefinedName definedName = new DefinedName()
    { Name = "test", Text="Sheet1!$B$2:$B$4" };       // Create a new range
definedNamesCol.Append(definedName);                  // Add it to the collection

workbook.Append(definedNamesCol);                     // Add collection to the workbook