gpt4 book ai didi

c# - 不包括文本框的 Word 自动化查找和替换

转载 作者:太空狗 更新时间:2023-10-30 01:06:48 24 4
gpt4 key购买 nike

我有一个带有文本框的 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 行。

最佳答案

有点乱,但这对我有用:

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);
}
}
}

之前:

Before

之后:

After

关于c# - 不包括文本框的 Word 自动化查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14256417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com