通过 C# Interop 向 word 文档添加空字段 [英] Add empty fields to a word document via C# Interop

查看:59
本文介绍了通过 C# Interop 向 word 文档添加空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过循环向 word 文档(通过 VSTO)添加几个空字段(即 ctrl+F9 快捷方式),但由于某些原因,文档中只出现最后一个.

I'm trying to add several empty fields (i.e ctrl+F9 shortcut) trough a loop to a word document (via VSTO) but for some reasons only the last one appears in the document.

有人可以帮我吗?

这是我使用的代码:

        Document doc = Globals.ThisAddIn.Application.ActiveDocument;
        if (doc == null)
            return;

        for (int i = 0; i < 5; i++)
        {
            Paragraph para = doc.Paragraphs.Add();
            object fieldType = WdFieldType.wdFieldEmpty;
            object text = "test" + i;
            object preserve = false;
            Field f = doc.Fields.Add(para.Range , ref fieldType, ref text, ref preserve);

        }

输出是:

{ test4 } 

此处为 MSDN 参考链接

推荐答案

它工作得很好,但很难看到.问题是所有 5 个字段都在彼此之上.可能是由于很快停止并且不清楚您想如何进行.任意地,将此代码附加到 for 循环体以使字段更可见:

It works just fine, but hard to see. Problem is that all 5 fields are on top of each other. Perhaps induced by stopping to soon and it is not clear how you want to proceed. Arbitrarily, append this code to the for-loop body to make the fields more visible:

f.ShowCodes = true;
para.Range.InsertAfter("\r\n");

这篇关于通过 C# Interop 向 word 文档添加空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆