我已经为MS Word创建了一个插件。有一个新的标签和一个按钮。我添加了一个新模板文件,其中包含RichTextContentControl。
WORD_APP = Globals.ThisAddIn.Application;
object oMissing = System.Reflection.Missing.Value;
object oTemplate = "E:\\Sandbox\\TemplateWithFields\\TemplateWithFields\\TemplateWithFields.dotx";
oDoc = WORD_APP.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
我想在RichTextContentControl中获取文本。如何在AddIn项目中访问RichTextContentControl的文本或内容?
最佳答案
可以按以下方式访问内容控件的文本:
string text = contentControl1.Range.Text;
此外,您可以通过多种方式迭代内容控件,仅选择特定类型的内容控件或与特定标签或标题匹配的内容控件。
这非常重要,因为您可能只想处理与特定类型或命名约定匹配的内容控件,请参见以下示例:
WORD_APP = Globals.ThisAddIn.Application;
object oMissing = System.Reflection.Missing.Value;
object oTemplate = "E:\\Sandbox\\TemplateWithFields\\TemplateWithFields\\TemplateWithFields.dotx";
Word.Document document = WORD_APP.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
//Iterate through ALL content controls
//Display text only if the content control is of type rich text
foreach (Word.ContentControl contentControl in document.ContentControls)
{
if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
{
System.Windows.Forms.MessageBox.Show(contentControl.Range.Text);
}
}
//Only iterate through content controls where the tag is equal to "RT_Controls"
foreach (Word.ContentControl contentControl in document.SelectContentControlsByTag("RT_Controls"))
{
if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
{
System.Windows.Forms.MessageBox.Show("Selected by tag - " + contentControl.Range.Text);
}
}
//Only iterate through content controls where the title is equal to "Title1"
foreach (Word.ContentControl contentControl in document.SelectContentControlsByTitle("Title1"))
{
if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
{
System.Windows.Forms.MessageBox.Show("Selected by title - " + contentControl.Range.Text);
}
}
关于c# - 使用C#从MS Word中的外接程序访问RichTextContentControl文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3061589/