admin管理员组

文章数量:1334923

I am currently trying to extract all images and their positions from an Excel file in C#. It works fine if the image is placed over the cells. In that case, I can use ClosedXML.Excel and retrieve them with the following code:

using (var workbook = new XLWorkbook(stream))
{
   var worksheet = workbook.Worksheet(1);
   foreach(var pictures in worksheet.Pictures) 
   {
          ..
   }
}

The problem is that if you insert the image into a cell, then Pictures becomes empty, and the image cannot be found.

So, then I tried using DocumentFormat.OpenXml, which at least allows me to locate the images like this:

using (SpreadsheetDocument document = SpreadsheetDocument.Open("C:\\test.xlsx", false))
{
    var package = document.GetPackage();

    foreach (var part in package.GetParts())
    {
        if (part.ContentType.StartsWith("image/"))
        {
            using (var stream = part.GetStream(FileMode.Open, FileAccess.Read))
            using (var fileStream = new FileStream("testimage.png", FileMode.Create, FileAccess.Write))
            {
                stream.CopyTo(fileStream);
            }
        }
    }
}

This gives me all the images, but it doesn't provide any information about their positions.

Anyone have an idea on how to get the position or what cell the image belongs too? And just to be clear, this is when the image is placed in the cell. If it is placed over the cell it works fine.

本文标签: How can I extract image placed inside a cell in excel with CStack Overflow