![](/img/trans.png)
[英]Can I find the location of text in a Word document using OpenXML SDK?
[英]How can I use OpenXML SDK 2.5 to copy formulas from a word document?
我必须使用带有C#的OpenXML SDK 2.5来复制一个word文档中的公式,然后将它们附加到另一个word文档中。 我尝试了下面的代码,它运行成功但是当我试图打开文件时,它说内容有问题。 我打开它忽略了警告,但没有显示那些公式。 它们只是空白块。
我的代码:
private void CreateNewWordDocument(string document, Exercise[] exercices)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
{
// Set the content of the document so that Word can open it.
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
SetMainDocumentContent(mainPart);
foreach (Exercise ex in exercices)
{
wordDoc.MainDocumentPart.Document.Body.AppendChild(ex.toParagraph().CloneNode(true));
}
wordDoc.MainDocumentPart.Document.Save();
}
}
// Set content of MainDocumentPart.
private void SetMainDocumentContent(MainDocumentPart part)
{
string docXml =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
<w:body><w:p><w:r><w:t>Exercise list!</w:t></w:r></w:p></w:body>
</w:document>";
using (Stream stream = part.GetStream())
{
byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
stream.Write(buf, 0, buf.Length);
}
}
发生这种情况是因为克隆段落时不会复制段落中可引用的所有内容。 Word XML格式由多个文件组成,其中一些文件相互引用。 如果将段落从一个文档复制到另一个文档,则还需要复制可能存在的任何关系。
OpenXML Productivity Tool可用于诊断这些错误。 您可以使用该工具打开文档并要求其验证文档。
我创建了一个测试文档,其中只包含一个超链接并运行您的代码以将内容复制到另一个文档。 当我尝试使用Word加载它时,我也遇到了错误,因此我在Productivity Tool中打开它并看到以下输出:
这表明超链接存储为段落中的关系而不是内联,我的新文件引用了不存在的关系。 解压缩原始文件和新文件并比较两者显示正在发生的事情:来自original的document.xml
:
原始的.rels
生成文件的document.xml
.rels
生成的文件
请注意,在生成的文件中,超链接引用了关系rId5,但在生成的文档关系文件中不存在。
值得注意的是,对于简单的源文档,代码可以正常工作,因为没有需要复制的关系。
有两种方法可以解决这个问题。 最简单的方法是只复制段落的文本 (你将失去所有的样式,图像,超链接等),但它非常简单。 你需要做的就是改变
wordDoc.MainDocumentPart.Document.Body.AppendChild(ex.toParagraph().CloneNode(true));
对于
Paragraph para = wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(ex.toParagraph().InnerText));
实现它的更复杂(也许是正确的)方法是找到关系并将它们复制到新文档中。 这样做的代码可能超出了我在这里写的范围,但是这里有一篇关于这个主题的有趣文章http://blogs.msdn.com/b/ericwhite/archive/2009/02/05/move- insert-delete-paragraph-in-word-processing-documents-using-open-xml-sdk.aspx 。
本博客文章的作者基本上是使用Powertools for OpenXML来查找关系并将它们从一个文档复制到另一个文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.