Search code examples
c#epplusepplus-4

How to get a shape/picture coordinates in pixels in an excel file (xlsx) using EPPlus


Has anyone succeeded in obtaining the x and y coordinate in pixels of a shape or a picture in a sheet in an excel 2010 file using epplus?


Solution

  • I finally found a solution using internal xml data, it seems that excel is using a unit for measure called EMU which is equal to 1/9525 pixel. the solution is below

    public static Rectangle GetDimensions(string shapeName, ExcelWorksheet sheet)
    {
      const int EMU = 9525;
      var shapeBaseNodexPath = string.Format("//*[@name='{0}']", shapeName);
    
      //get node that contains name of the shape
      var shapeNameNode = sheet.Drawings.DrawingXml.SelectSingleNode(shapeBaseNode);
    
      if (shapeNameNode == null)
        throw new ArgumentException("Invalid shape name");
      //go 2 levels up and select shape properties node <a:xfrm> node
      var propertiesNode = shapeNameNode
        .SelectSingleNode("../../*[local-name() = 'spPr']/*[local-name() = 'xfrm']");
      if (propertiesNode == null)
        throw new InvalidOperationException("Could not parse Excel file xml data");
    
      //get coodinates and size nodes
      var locationNode = propertiesNode.SelectSingleNode("*[local-name() = 'off']");
      var sizeNode = propertiesNode.SelectSingleNode("*[local-name() = 'ext']");
    
      //create Rectangle
      int x, y, w, h = 0;
      x = int.Parse(locationNode.Attributes["x"].Value) / EMU;
      y = int.Parse(locationNode.Attributes["y"].Value) / EMU;
      w = int.Parse(sizeNode.Attributes["cx"].Value) / EMU;
      h = int.Parse(sizeNode.Attributes["cy"].Value) / EMU;
    
      return new Rectangle(x, y, w, h);
    }