2

可能重复:
如何检查单元格是否有图片?
OpenXML:Excel,提取单元格文本和图像/图片数据

我有一个包含 4 个图像的 Excel 文档,每个图像位于单元格 A1、A2、A3、A4 中

我可以遍历工作表中的所有图像,但我需要能够编辑此函数以提供“A1”和“A2”中的图像

    [Test]
    public void IterateThruImages()
    {
        WorkbookPart wbPart = document.WorkbookPart;
        var workSheet = wbPart.WorksheetParts.FirstOrDefault();

        foreach(ImagePart i in workSheet.DrawingsPart.GetPartsOfType<ImagePart>())
        {
            Stream stream = i.GetStream();
            long length = stream.Length;
            byte[] byteStream = new byte[length];
            stream.Read(byteStream, 0, (int)length);

            var imageAsString = Convert.ToBase64String(byteStream);
        }
    }
4

1 回答 1

2

诀窍是获取图像的关系 ID“rId”。您可以通过获取相关行/列的 TwoCellAnchor 来获得它。然后获取嵌入。使用它来获取图像。

    [Test]
    public void GetImageRelationshipIdAndImageOfThatId()
    {
        string row = "1";
        string col = "0";

        WorkbookPart wbPart = document.WorkbookPart;
        var workSheet = wbPart.WorksheetParts.FirstOrDefault();

        TwoCellAnchor cellHoldingPicture = workSheet.DrawingsPart.WorksheetDrawing.OfType<TwoCellAnchor>()
             .Where(c => c.FromMarker.RowId.Text == row && 
                    c.FromMarker.ColumnId.Text == col).FirstOrDefault();

        var picture = cellHoldingPicture.OfType<DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture>().FirstOrDefault();
        string rIdofPicture = picture.BlipFill.Blip.Embed;

        Console.WriteLine("The rID of this Anchor's [{0},{1}] Picture is '{2}'" ,row,col, rIdofPicture);

        ImagePart imageInThisCell = (ImagePart)workSheet.DrawingsPart.GetPartById(rIdofPicture);

    }
于 2012-08-16T21:33:59.700 回答