【问题标题】:word interop replace tag with document contentword interop 用文档内容替换标签
【发布时间】:2015-02-24 11:27:53
【问题描述】:

我正在尝试使用 Word Interop 尝试将 Word 文档中的 TAG 替换为另一个文档的内容。

例如,我必须处理具有#TAG#123456789# 之类标签的example.doc,然后我必须复制123456789.doc 并将内容粘贴到example.doc 中替换标签#TAG#123456789#

文档123456789.doc 有它的表格、图像等等。

到目前为止,我可以在 example.doc 中找到标签并获取 123456789.doc,但除了文本替换之外,我没有找到任何可行的方法。

我正在考虑一种新方法,通过使用以下范围附加部分文档来生成新文档:

  1. example.doc 从开头附加到 TAG 的开头。
  2. 追加123456789.doc
  3. 将标签末尾的example.doc 的其余部分附加到文档的末尾。

【问题讨论】:

  • 我在文档 1 中定义了一个范围。Microsoft.Office.Interop.Word.Range rng = document.Range(ref docStart, ref docEnd); 我选择并复制整个第二个文档:object start = SubDoc.Content.Start; object end = SubDoc.Content.End; SubDoc.Range(ref start, ref end).Copy(); 我复制了范围 1 中的内容:rng.Paste(); 并保存文档:document.Save();但是,我无法复制图像,我该怎么办?很抱歉回答,但无法在评论中添加返回行...
  • 如果我在粘贴“Microsoft.Office.Interop.Word.Range rng = document.Range(ref docStart, ref docEnd); 时将目标范围设置为文档的结尾object docStart = document.Content.End - 1; object docEnd = document.Content.End; rng.Paste();´ 它粘贴所有包括图像。如果我选择范围来替换单词 ej: object docStart = document.Content.Words[i - 8].Start; object docEnd = document.Content.Words[i].End; 当我做同样的粘贴时,它只会粘贴第一个单词。

标签: c# ms-word


【解决方案1】:

看来您已经接近解决方案了。当您在文档中找到标记并选择它时,您可以使用 WordApp.Selection.InsertFile() 方法将来自另一个文档的内容插入到该选择中。

确保首先做出选择很重要。

示例方法:

        /// <summary>
        /// This method adds a file to the Word.ApplicationClass object's current selection.
        /// Has been tested with word (*.doc)documents but not with other office files.
        /// Other files may work also with this method.
        /// Tested with the Microsoft 9.0 Object Library ( COM )
        /// </summary>
        /// <param name="WordApp">The Word.ApplicationClass object</param>
        /// <param name="DirLocation">A string that contains the file directory location.</param>
        /// <param name="FileName">A string that contains the file name within the directory location.</param>
        public static void InsertFile(Word.ApplicationClass WordApp, string DirLocation, string FileName)
        {
            try
            {
                object j_NullObject = System.Reflection.Missing.Value;

                WordApp.Selection.InsertFile(DirLocation + FileName, ref j_NullObject, ref j_NullObject, ref j_NullObject, ref j_NullObject);
            }

            //An Exception will occur when the Directory location and filename does not exist.
            //An Exception may also occur when the Word.ApplicationClass has no Selection to add
            //the file to.
            catch (Exception e)
            {
                //show the user the error message
                MessageBox.Show(e.Message);

                //log the error
                //ErrorLog.LogError(e);
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2019-05-04
    • 2015-01-31
    相关资源
    最近更新 更多