我尝试改变的Word文件的文档模板自动化的过程。如何文档链接到不同的结构化模板
如果模板类似的结构,即它们都使用heading1
,那么当文档被链接到新的模板,它的工作原理。
但是,模板结构完全不同,heading1
不再使用,现在是section1
。我如何使用代码更改这些部分标题?沿线if(heading1) rename to section1;
我正在使用Interop.Word
来执行这些操作。
下面是我使用的代码:
public string UpdateDocumentWithNewTemplate(string document, string theme, string template, Word.Application wordApp)
{
try
{
object missing = System.Reflection.Missing.Value;
Word.Document aDoc = null;
object notReadOnly = false;
object isVisible = false;
wordApp.Visible = false;
// create objects from variables for wordApp
object documentObject = document;
// open existing document
aDoc = wordApp.Documents.Open(ref documentObject, ref missing, ref notReadOnly, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible,
ref missing, ref missing, ref missing, ref missing);
aDoc.Activate();
// set template and theme to overwrite the existing styles
aDoc.CopyStylesFromTemplate(template);
aDoc.ApplyDocumentTheme(theme);
aDoc.UpdateStyles();
// save the file with the changes
aDoc.SaveAs(ref documentObject, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
// close the document
aDoc.Close(ref missing, ref missing, ref missing);
if (aDoc != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(aDoc);
aDoc = null;
return documentObject.ToString();
}
catch (Exception exception)
{
return "Error: " + exception;
}
}
感谢您的详细解释。使用OpenXml和Interop是否是不好的做法?使用Interop时,我似乎无法删除/应用标题。 – PurpleSmurph
你可以使用什么工作:-)我的代码(根据你的情况调整)不起作用吗?在我发布之前,它在我的测试中确实有效。文档是否受到任何保护? –
我不知道有什么问题,似乎没有被保护,但我们确实使用共享驱动器和共享点,最后我创建了一个新文档并将原始内容复制/格式粘贴到新的文档中,然后应用模板。我测试了你的代码,它的工作原理=),我将在稍后将它集成到新版本中。 – PurpleSmurph