将Word文档中的书签替换为另一个Word文档的内容

时间:2013-05-17 17:56:59

标签: c# .net vsto

我希望将word文档中的书签替换为另一个word文档的全部内容。我希望按照以下方式做一些事情,但是附加xml似乎不够,因为它不包括图片。

using Word = Microsoft.Office.Interop.Word;
...

Word.Application wordApp = new Word.Application();
Word.Document doc = wordApp.Documents.Add(filename);
var bookmark = doc.Bookmarks.OfType<Bookmark>().First();

var doc2 = wordApp.Documents.Add(filename2);

bookmark.Range.InsertXML(doc2.Contents.XML);

第二个文档包含一些图像和几个文本表。


更新:使用XML取得的进展,但仍然不满足添加图片。

2 个答案:

答案 0 :(得分:1)

你已经深入了解。

如果您正在使用对象模型(bookmark.Range)并尝试插入图片,则可以使用剪贴板或bookmark.Range.InlineShapes.AddPicture(...)。如果您尝试插入整个文档,则可以复制/粘贴第二个文档:

 Object objUnit = Word.WdUnits.wdStory;
 wordApp.Selection.EndKey(ref objUnit, ref oMissing);         
 wordApp.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);

如果您使用的是XML,则可能会出现其他问题,例如格式,图片,页眉/页脚无法正确显示。

根据任务的不同,使用DocumentBuilder和OpenXML SDK可能会更好。如果您正在编写Word插件,则可以使用对象API,如果您使用OpenXML SDK和DocumentBuilder处理没有Word的文档,它可能会执行相同的操作。 DocumentBuilder的问题是,如果它不起作用,那么尝试的解决方法并不多。如果您尝试对其进行故障排除,它是开源的,而不是最干净的代码。

答案 1 :(得分:0)

您可以使用openxml SDK和文档构建器执行此操作。这里概述了你需要的东西

1&GT;在主文档中注入插入键

public WmlDocument GetProcessedTemplate(string templatePath, string insertKey)
{
    WmlDocument templateDoc = new WmlDocument(templatePath);
    using (MemoryStream mem = new MemoryStream())
    {
        mem.Write(templateDoc.DocumentByteArray, 0, templateDoc.DocumentByteArray.Length);
        using (WordprocessingDocument doc = WordprocessingDocument.Open([source], true))                            
        {
            XDocument xDoc = doc.MainDocumentPart.GetXDocument();
            XElement bookMarkPara = [get bookmarkPara to replace];
            bookMarkPara.ReplaceWith(new XElement(PtOpenXml.Insert, new XAttribute("Id", insertKey)));
            doc.MainDocumentPart.PutXDocument();
        }
        templateDoc.DocumentByteArray = mem.ToArray();
    }
    return templateDoc;
}

2 - ;使用文档构建器合并

List<Source> documentSources = new List<Source>();
var insertKey = "INSERT_HERE_1";
var processedTemplate = GetProcessedTemplate([docPath], insertKey);  
documentSources.Add(new Source(processedTemplate, true));
documentSources.Add(new Source(new WmlDocument([docToInsertFilePath]), insertKey));
DocumentBuilder.BuildDocument(documentSources, [outputFilePath]);