简体   繁体   English

将格式化的文本插入Word文档

[英]Insert formatted text to Word document

I insert text to a Word document. 我在Word文档中插入文本。 This is done by selection.TypeText("text"); 这是通过selection.TypeText("text");完成的selection.TypeText("text");

I would like to insert formatted text to a Word document, something like: 我想将带格式的文本插入到Word文档中,例如:

public override void InsertText(string content, string format)
{
    selection.Style = format; //something like this
    selection.Font.Name = "Heading 1"; //or like this
    selection.TypeText(content);
}

Any ideas? 有任何想法吗?

For a Word Document-Level Customization where Microsoft.Office.Interop.Word is referenced, this works: 对于其中引用了Microsoft.Office.Interop.Word的Word文档级自定义,此方法有效:

this.ActiveWindow.Selection.Range.Font.Name = "Arial";
this.ActiveWindow.Selection.Range.Font.Size = 36;

You can also assign the range of a selection to a range variable and then apply formats to the variable as in: 您还可以将选择范围分配给范围变量,然后将格式应用于该变量,如下所示:

Word.Range myRange = this.ActiveWindow.Selection.Range;
myRange.Font.Size = 18;
myRange.Font.Name = "Arial";

EDIT (Response to OP's question in comments) 编辑(在评论中回复OP的问题)

To apply a Heading style to the selected text assign one of Word's WdBuiltinStyle enumeration members: 要将标题样式应用于所选文本,请分配Word的WdBuiltinStyle枚举成员之一:

object headingStyle = Word.WdBuiltinStyle.wdStyleHeading1;
this.ActiveWindow.Selection.Range.set_Style(ref headingStyle);

To view the full list of enumeration members, see this: 要查看枚举成员的完整列表,请参见:

MSDN: WdBuiltinStyle enumeration MSDN:WdBuiltinStyle枚举

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM