Reading Worksheet Cell Value Using OpenXML SDK

public string XLGetCellValue(string fileName, 
  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 (Package xlPackage = Package.Open(
    fileName, FileMode.Open, FileAccess.Read))
  {
    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 = 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.
      XmlDocument doc = new XmlDocument();
      doc.Load(documentPart.GetStream());

      //  Create a namespace manager, so you can search.
      //  Add a prefix (d) for the default namespace.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("d", worksheetSchema);
      nsManager.AddNamespace("s", sharedStringSchema);

      // Next code block goes here.
  return cellValue;
}

Last edited Dec 5, 2013 at 11:53 AM by assadmahmood, version 1