OpenXml: Determining the Image in a Cell in Excel [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-20 03:21:58

问题


Possible Duplicate:
How to check if a cell has a picture?
OpenXML: Excel, extracting Cell text and Image/Picture data

I have An Excel document with 4 images, each in a cell A1,A2,A3,A4

I can iterate thru all the images in the worksheet, but I need to be able to edit this function to give me the image in "A1" and "A2" for instance

    [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);
        }
    }

回答1:


The trick is to get the relationship id "rId" of the image. You get that by getting the TwoCellAnchor of the row/col in question. Then get the Embed. Use that to get the image.

    [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);

    }


来源:https://stackoverflow.com/questions/11994216/openxml-determining-the-image-in-a-cell-in-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!