本文介绍了OpenXML的:确定图像在Excel单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含4张图片的Excel文档,每个都在单元格A1,A2,A3,A4中
I have An Excel document with 4 images, each in a cell A1,A2,A3,A4
我可以迭代工作表中的所有图像,但我需要能够编辑这个函数给我的图像在A1和A2例如
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);
}
}
推荐答案
诀窍是获取图像的关系idrId。你得到的行/ col的TwoCellAnchor有问题。然后获取Embed。使用它来获取图像。
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);
}
这篇关于OpenXML的:确定图像在Excel单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!