【问题标题】:Word Automation Find and Replace not including Text BoxesWord 自动化查找和替换不包括文本框
【发布时间】:2014-01-08 17:40:31
【问题描述】:

我有一个带有文本框的 word 文档。当我在主文档中运行自动查找并替换其匹配项时,但在文本框中不匹配任何内容。我如何告诉查找和替换功能包括文本框。

Word.Range range = objDoc.Content;

object findtext = Field;
object findreplacement = Value;
object findwrap = WdFindWrap.wdFindContinue;
object findreplace = WdReplace.wdReplaceAll;

range.Find.Execute(findtext, missing, missing, missing, missing, missing, missing, findwrap, missing, findreplacement, findreplace);

我怀疑我需要更改 range = objDoc.content 行。

【问题讨论】:

标签: c# ms-word office-interop


【解决方案1】:

有点乱,但这对我有用:

using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main()
        {
            const string documentLocation = @"C:\temp\Foo.docx";
            const string findText = "Foobar";
            const string replaceText = "Woo";

            FindReplace(documentLocation, findText, replaceText);
        }

        private static void FindReplace(string documentLocation, string findText, string replaceText)
        {
            var app = new Application();
            var doc = app.Documents.Open(documentLocation);

            var range = doc.Range();

            range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);

            var shapes = doc.Shapes;

            foreach (Shape shape in shapes)
            {
                var initialText = shape.TextFrame.TextRange.Text;
                var resultingText = initialText.Replace(findText, replaceText);
                shape.TextFrame.TextRange.Text = resultingText;
            }

            doc.Save();
            doc.Close();

            Marshal.ReleaseComObject(app);
        }
    }
}

之前:

之后:

【讨论】:

  • 太棒了 - 花了很长时间试图找出文本框的位置。 doc.Shapes 是赢家。
  • 顺便说一句,您仍然可以在 TextFrame 的范围内使用 Find。它只需要一个单独的调用。只是有点烦人。
  • 对我们的项目也很有帮助!一个小评论:形状可能没有文本(我们有一些形状确实有,有些没有,所以 shape.TextFrame.TextRange.Text 可能会抛出一个必须处理的异常......
  • @AmittaiShapira 好点,我猜 C#6 你现在可以使用 shape?.TextFrame?.TextRange?.Text
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 2013-09-07
  • 2015-01-31
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
相关资源
最近更新 更多