PuK*_*PuK 5 c# excel ms-word openxml-sdk
我必须实现一个Microsoft Word文档生成器,其中嵌入了excel图形.我的一个限制是使我生成的docx与Microsoft word 2010和2003 +兼容包一起工作.
我没有设法使它适用于他们两个.我可以使它适用于Word 2010,但该文档不适用于2003,反之亦然.
经过多次搜索使其适用于Word 2003后,我在我的代码中添加了这个:
private static void Word2003(ChartPart importedChartPart, MainDocumentPart mainDocumentPart, Stream fileStream)
{
var ext = new ExternalData { Id = "rel" + 5 };
importedChartPart.ChartSpace.InsertAt(ext, 3);
var fi = new FileInfo(@"generated.xlsx");
importedChartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/package", new Uri(fi.Name, UriKind.Relative), "rel5");
EmbeddedPackagePart embeddedObjectPart = mainDocumentPart.AddEmbeddedPackagePart(@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Stream copyStream = new MemoryStream();
fileStream.CopyTo(copyStream);
embeddedObjectPart.FeedData(copyStream);
}
Run Code Online (Sandbox Code Playgroud)
但此时生成的文档无法与Word 2010一起使用.如果我删除这两个lignes:
var ext = new ExternalData { Id = "rel" + 5 };
importedChartPart.ChartSpace.InsertAt(ext, 3);
Run Code Online (Sandbox Code Playgroud)
从以前的代码,它适用于Word 2010,但不适用于Word 2003.
我尝试了几件事,但我没有设法让它适用于每个案例.
你可以在这里找到这一小段代码
先决条件是Excel文件的模板,其中包含图表和图形.
编辑:生成的文档始终与Microsoft Office 2007一起使用(有两个有问题的代码行).我仍在寻求解决方案!
我终于找到了解决方案!
问题是由于两件事:我没有正确地放置外部数据而外部关系是错误的.
此代码使其有效:
private static void Word2003(ChartPart importedChartPart, MainDocumentPart mainDocumentPart, Stream fileStream)
{
// Add of the external data id
ExternalData ext = new ExternalData { Id = "rel" + 5 };
AutoUpdate autoUpdate = new AutoUpdate{ Val = false};
ext.Append(autoUpdate);
importedChartPart.ChartSpace.Append(ext);
// Set of the relationship
var fi = new FileInfo(@"generated.xlsx");
importedChartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject", new Uri(fi.Name, UriKind.Relative), "rel5");
// Link to the embedded file
EmbeddedPackagePart embeddedObjectPart = mainDocumentPart.AddEmbeddedPackagePart(@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Stream copyStream = new MemoryStream();
fileStream.CopyTo(copyStream);
embeddedObjectPart.FeedData(copyStream);
}
Run Code Online (Sandbox Code Playgroud)
现在生成的Word文档适用于Word 2003,2007和2010.
也许这会对某人有所帮助!