How to get sheet name(s) from OpenXml document (Excel 2007)

by admin 17. June 2008 14:28

Below you'll find code snippet for reading Excel Sheet names from Office 2007 Excel document

public static List<string> GetSheetInfo(string fileName)
        {
            //  Fill this collection with a list of all the sheets.
            List<string> sheets = new List<string>();

            using (Microsoft.Office.DocumentFormat.OpenXml.Packaging.SpreadsheetDocument xlPackage = Microsoft.Office.DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(fileName, false))
            {
                Microsoft.Office.DocumentFormat.OpenXml.Packaging.WorkbookPart workbook = xlPackage.WorkbookPart;
                System.IO.Stream workbookstr = workbook.GetStream();
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(workbookstr);

                System.Xml.XmlNamespaceManager nsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);
                nsManager.AddNamespace("default", doc.DocumentElement.NamespaceURI);
                System.Xml.XmlNodeList nodelist = doc.SelectNodes("//default:sheets/default:sheet", nsManager);

                foreach (System.Xml.XmlNode node in nodelist)
                {
                    string sheetName = string.Empty;
                    sheetName = node.Attributes["name"].Value;
                    sheets.Add(sheetName);
                }
            }
            return sheets;
        }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c# | OpenXml

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar