问题
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