Retrieve a dictionary of all named ranges in a spreadsheet document

2016-01-15 06:49:26 Written by  support iceblue
Rate this item
(0 votes)

class Program
    {
        static void Main(string[] args)
        {
            var result = GetDefinedNames(@"..\..\Documents\Sheet10.xlsx");
            foreach (var dn in result)
                Console.WriteLine("{0} {1}", dn.Key, dn.Value);
            Console.ReadLine();
        }
        public static Dictionary GetDefinedNames(String fileName)
        {
            // Given a workbook name, return a dictionary of defined names.
            // The pairs include the range name and a string representing the range.
            var returnValue = new Dictionary();

            // Open the spreadsheet document for read-only access.
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
            {
                // Retrieve a reference to the workbook part.
                var wbPart = document.WorkbookPart;

                // Retrieve a reference to the defined names collection.
                DefinedNames definedNames = wbPart.Workbook.DefinedNames;

                // If there are defined names, add them to the dictionary.
                if (definedNames != null)
                {
                    foreach (DefinedName dn in definedNames)
                        returnValue.Add(dn.Name.Value, dn.Text);
                }
            }
            return returnValue;
        }
    }