如何使用C#直接在Word文本框中写入文本?

如何使用C#直接在Word文本框中写入文本?,c#,visual-studio,ms-word,word-interop,C#,Visual Studio,Ms Word,Word Interop,我想使用C#将一些文本写入现有的word文本框。 实际上什么都没发生,我也不知道为什么。 也许有人能帮我 我的方法: Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document

我想使用C#将一些文本写入现有的word文本框。 实际上什么都没发生,我也不知道为什么。 也许有人能帮我

我的方法:

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

void SearchTextBox(Microsoft.Office.Interop.Word.Document oDoc, string name, string newContent)
{
    foreach (Microsoft.Office.Interop.Word.Shape shape in oDoc.Shapes)
    {
        if (shape.Name == name)
        {
            shape.TextFrame.TextRange.Text = newContent;
            return;
        }
    }
}
电话:

解决方案如下:

using Word = Microsoft.Office.Interop.Word

var WORD = new Word.Application();
Word.Document doc   = WORD.Documents.Open(@PATH_APP);
doc.Activate();

foreach (Microsoft.Office.Interop.Word.Shape shape in WORD.ActiveDocument.Shapes)
{
    if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
        if (shape.AlternativeText.Contains("MY_FIELD_TO_OVERWRITE_OO1"))
        {       
             shape.TextFrame.TextRange.Text="MY_NEW_FIELD_VALUE";
        }

    }
}

doc.Save();

文本框是否可能位于某个基本级别形状内?如果形状可以嵌套在其他形状中,则可能需要进行一些递归(只是猜测,没有使用像这样的word),这看起来像是VBA UserForms类型文本框中的ActiveX控件,而不是形状,这解释了为什么代码没有显示任何效果。除非你有很好的理由使用它,否则我不推荐它,尤其是对于C。内容控件可能是更好的解决方案。或者,如果可以为表单保护文档,则可以使用表单字段。或者画一个文本框,然后你的代码就可以工作了…找到了一个解决方法。使用书签写入文本框坐标
using Word = Microsoft.Office.Interop.Word

var WORD = new Word.Application();
Word.Document doc   = WORD.Documents.Open(@PATH_APP);
doc.Activate();

foreach (Microsoft.Office.Interop.Word.Shape shape in WORD.ActiveDocument.Shapes)
{
    if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
        if (shape.AlternativeText.Contains("MY_FIELD_TO_OVERWRITE_OO1"))
        {       
             shape.TextFrame.TextRange.Text="MY_NEW_FIELD_VALUE";
        }

    }
}

doc.Save();