4

我正在编写代码以将单元格中的单元格和图片/图像从 Excel 文档中提取到数据库中。

使用此代码,我可以获得不是图片的单元格值。

但是,Cell 对象中没有图片。请注意,每一行都以图像开头。

A1- Picture
B1- Text
C1- Text and so on. 

如何从“A”列获取图像?

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

        foreach (Row r in workSheet.Worksheet.Descendants<Row>())
        {
            //Note only has Colum B,C. Not A as A has an image???
            foreach(Cell c in r.ChildElements)
            {
                foreach(object o in c.ChildElements)
                {
                    Console.WriteLine(c.CellReference + " " + o.ToString());
                }
            }
        }
4

1 回答 1

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

        foreach (ImagePart i in workSheet.DrawingsPart.ImageParts)
        {
            var rId = workSheet.DrawingsPart.GetIdOfPart(i);

            Stream stream = i.GetStream();
            long length = stream.Length;
            byte[] byteStream = new byte[length];
            stream.Read(byteStream, 0, (int)length);

            var imageAsString = Convert.ToBase64String(byteStream);
            Console.WriteLine("The rId of this Image is '{0}'",rId);
        }
    }


    [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:34:55.007 回答