可能重复:
How to check if a cell has a picture?
OpenXML: Excel, extracting Cell text and Image/Picture data
我有一个带有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);
}
}
答案 0 :(得分: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);
}