Word 文档包含嵌入式图表,我想使用打开的 xml 将相同的图表复制并粘贴到另一个文档中。我使用了以下代码,但粘贴图表后文件已损坏。你能找出我的错误吗?
这里 doc 是我的原始文件 WordprocessingDocument 对象。
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Create("C:\\Sample.docx", WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
if (mainPart == null)
{
mainPart = wordprocessingDocument.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
}
var chart = mainPart.AddNewPart<ChartPart>();
chart.FeedData(doc.MainDocumentPart.ChartParts.First().GetStream());
string type = doc.MainDocumentPart.ChartParts.ElementAt(0).EmbeddedPackagePart.ContentType;
var embdedPkgPart = mainPart.AddEmbeddedPackagePart(type);
embdedPkgPart.FeedData(doc.MainDocumentPart.ChartParts.ElementAt(0).EmbeddedPackagePart.GetStream());
string rellId = mainPart.GetIdOfPart(chart);
string uyo = chart.CreateRelationshipToPart(embdedPkgPart);
uyo.ToString();
AddChart(wordprocessingDocument, rellId);
wordprocessingDocument.MainDocumentPart.Document.Save();
}
public static void AddChart(WordprocessingDocument wordDoc, string relId)
{
DocumentFormat.OpenXml.Wordprocessing.Drawing element =
new Drawing(
new Inline(
new Extent()
{
Cx = 5486400,
Cy = 3200400
},
new DW.EffectExtent()
{
LeftEdge = 19050L,
TopEdge = 0L,
RightEdge = 19050L,
BottomEdge = 0L
},
new DocProperties()
{
Id = (UInt32Value)5U,
Name = "Chart 5"
},
new DocumentFormat.OpenXml.Drawing.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
new GraphicFrameLocks() { NoChangeAspect = true }),
new Graphic(
new GraphicData(
new DocumentFormat.OpenXml.Drawing.Charts.ChartReference() { Id = relId }
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U
}
);
wordDoc.MainDocumentPart.Document.Body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)));
}