我正在开发一个库,它将获得一个excel并删除excel包含的每个图像。
我正在使用库DocumentFormat.OpenXml V. 2.7.2,我可以在每张纸上找到文档所有的图像,我可以删除每张图片但是当我检查输出excel时它有相同的图片来源一张它没有删除任何图片。
我的代码是:
public void RemoveImagesWithOpenXML(string sourceFilePath, string targetFilePath)
{
SpreadsheetDocument excel = SpreadsheetDocument.Open(sourceFilePath, true);
excel.WorkbookPart.WorksheetParts.ForEach(s =>
{
List<ImagePart> list = new List<ImagePart>();
List<Drawing> drwdDeleteParts = new List<Drawing>();
List<Drawing> drwParts = new List<Drawing>(s.RootElement.Descendants<Drawing>());
foreach (var img in s.ImageParts)
{
string uri = img.Uri.ToString();
list.Add(img);
IEnumerable<Drawing> drawings = drwParts
.Where(d => d.Descendants<Picture>()
.Any(p => p.BlipFill.Blip.Embed == s.GetIdOfPart(img)));
foreach (var drawing in drawings)
{
if (drawing != null && !drwdDeleteParts.Contains(drawing)) drwdDeleteParts.Add(drawing);
}
}
foreach (var d in drwdDeleteParts) d.Remove();
s.DeleteParts(list);
});
excel.SaveAs(targetFilePath);
}