How to get cell value from OpenXml document (Excel 2007)

by admin 17. June 2008 14:34

Below you'll find code snippet for reading cell value(s) from Office 2007 Excel document.

In order to get this working you'll need to add refference to WindowsBase.dll .

sheetName="Sheet1"; addressName="E9";

public static string GetCellValue(string filePath, string sheetName, string addressName)
        {
            //  Return the value of the specified cell.
            const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
            const string worksheetSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
            const string sharedStringsRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
            const string sharedStringSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

            string cellValue = null;

            //  Retrieve the stream containing the requested
            //  worksheet's info:
            using (System.IO.Packaging.Package xlPackage = System.IO.Packaging.Package.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                System.IO.Packaging.PackagePart documentPart = null;
                Uri documentUri = null;

                //  Get the main document part (workbook.xml).
                foreach (System.IO.Packaging.PackageRelationship relationship in xlPackage.GetRelationshipsByType(documentRelationshipType))
                {
                    //  There should only be one document part in the package.
                    documentUri = System.IO.Packaging.PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                    documentPart = xlPackage.GetPart(documentUri);
                    //  There should only be one instance,
                    //  but get out no matter what.
                    break;
                }

                if (documentPart != null)
                {
                    // Load the contents of the workbook.
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(documentPart.GetStream());
                    //  Create a namespace manager, so you can search.
                    //  Add a prefix (d) for the default namespace.
                    System.Xml.NameTable nt = new System.Xml.NameTable();
                    System.Xml.XmlNamespaceManager nsManager = new System.Xml.XmlNamespaceManager(nt);
                    nsManager.AddNamespace("d", worksheetSchema);
                    nsManager.AddNamespace("s", sharedStringSchema);

                    string searchString = string.Format("//d:sheet[@name='{0}']", sheetName);
                    System.Xml.XmlNode sheetNode = doc.SelectSingleNode(searchString, nsManager);
                    if (sheetNode != null)
                    {
                        //  Get the relId attribute:
                        System.Xml.XmlAttribute relationAttribute = sheetNode.Attributes["r:id"];
                        if (relationAttribute != null)
                        {
                            string relId = relationAttribute.Value;

                            //  First, get the relation between the
                            // document and the sheet.
                            System.IO.Packaging.PackageRelationship sheetRelation = documentPart.GetRelationship(relId);
                            Uri sheetUri = System.IO.Packaging.PackUriHelper.ResolvePartUri(documentUri, sheetRelation.TargetUri);
                            System.IO.Packaging.PackagePart sheetPart = xlPackage.GetPart(sheetUri);

                            //  Load the contents of the workbook.
                            System.Xml.XmlDocument sheetDoc = new System.Xml.XmlDocument(nt);
                            sheetDoc.Load(sheetPart.GetStream());

                            System.Xml.XmlNode cellNode = sheetDoc.SelectSingleNode(string.Format("//d:sheetData/d:row/d:c[@r='{0}']", addressName), nsManager);
                            if (cellNode != null)
                            {
                                //  Retrieve the value. The value may be stored within
                                //  this element. If the "t" attribute contains "s", then
                                //  the cell contains a shared string, and you must look
                                //  up the value individually.
                                System.Xml.XmlAttribute typeAttr = cellNode.Attributes["t"];
                                string cellType = string.Empty;
                                if (typeAttr != null)
                                {
                                    cellType = typeAttr.Value;
                                }

                                System.Xml.XmlNode valueNode = cellNode.SelectSingleNode("d:v", nsManager);
                                if (valueNode != null)
                                {
                                    cellValue = valueNode.InnerText;
                                }

                                //  Check the cell type. At this point, this code only checks
                                //  for booleans and strings individually.
                                if (cellType == "b")
                                {
                                    if (cellValue == "1")
                                    {
                                        cellValue = "TRUE";
                                    }
                                    else
                                    {
                                        cellValue = "FALSE";
                                    }
                                }
                                else if (cellType == "s")
                                {
                                    //  Go retrieve the actual string from the associated string file.
                                    foreach (System.IO.Packaging.PackageRelationship stringRelationship in documentPart.GetRelationshipsByType(sharedStringsRelationshipType))
                                    {
                                        //  There should only be one shared string reference,
                                        // so you exit this loop immediately.
                                        Uri sharedStringsUri = System.IO.Packaging.PackUriHelper.ResolvePartUri(documentUri, stringRelationship.TargetUri);
                                        System.IO.Packaging.PackagePart stringPart = xlPackage.GetPart(sharedStringsUri);
                                        if (stringPart != null)
                                        {

                                            //  Load the contents of the shared strings.
                                            System.Xml.XmlDocument stringDoc = new System.Xml.XmlDocument(nt);
                                            stringDoc.Load(stringPart.GetStream());

                                            //  Add the string schema to the namespace manager:
                                            nsManager.AddNamespace("s", sharedStringSchema);

                                            int requestedString = Convert.ToInt32(cellValue);
                                            string strSearch = string.Format("//s:sst/s:si[{0}]", requestedString + 1);
                                            System.Xml.XmlNode stringNode = stringDoc.SelectSingleNode(strSearch, nsManager);
                                            if (stringNode != null)
                                            {
                                                cellValue = stringNode.InnerText;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return cellValue;
            }

Currently rated 3.0 by 2 people

  • Currently 3/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