word文档包含嵌入式图表,我希望使用open 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)));
}
答案 0 :(得分:4)
public static void WriteChartParts(MainDocumentPart sourcePart, MainDocumentPart destnPart)
{
var paras = sourcePart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>();
var drawingElements = from run in paras
where run.Descendants<Drawing>().Count() != 0
select run.Descendants<Drawing>().First();
sourcePart.ChartParts.ForAll(chartPart =>
{
destnPart.AddPart<ChartPart>(chartPart, sourcePart.GetIdOfPart(chartPart));
});
drawingElements.ForAll(drw =>
{
destnPart.Document.Body.Append((drw as OpenXmlElement).Clone() as OpenXmlElement);
});
destnPart.Document.Save();
}