【发布时间】:2014-07-10 20:37:24
【问题描述】:
我必须使用带有 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);
}
}
【问题讨论】:
-
如果不知道您的练习[]-array 的内容是什么,这有点难以回答。
-
练习对象包含一个段落,现在就是这样。在上面的代码中,练习对象的唯一用法是返回该段落的“ex.toParagraph()”。我希望有人能告诉我解决方案。我被这个问题困住了。