如何在 Office 编程中使用命名自变量和可选自变量

命名参数和可选参数增强了 C# 编程中的便利性、灵活性和可读性。 另外,这些功能显著方便了对 COM 接口(如 Microsoft Office 自动化 API)的访问。

重要

VSTO (Visual Studio Tools for Office) 依赖于 .NET Framework。 COM 加载项也可以使用 .NET Framework 编写。 不能使用 .NET Core 和 .NET 5+(最新版本的 .NET)创建 Office 加载项。 这是因为 .NET Core/.NET 5+ 无法在同一进程中与 .NET Framework 协同工作,并可能导致加载项加载失败。 可以继续使用 .NET Framework 编写适用于 Office 的 VSTO 和 COM 加载项。 Microsoft 不会更新 VSTO 或 COM 加载项平台以使用 .NET Core 或 .NET 5+。 可以利用 .NET Core 和 .NET 5+(包括 ASP.NET Core)创建 Office Web 加载项的服务器端。

在下面的示例中,方法 ConvertToTable 具有 16 个参数,用于表示表的各种特性,例如列数和行数、格式设置、边框、字体以及颜色。 由于大多数时候都不需要为所有 16 个参数指定特定值,因此所有这些参数都是可选的。 但是,如果没有命名参数和可选参数,则必须提供值或占位符值。 有了命名参数和可选参数,则只需为项目所需的参数指定值。

必须在计算机上安装 Microsoft Office Word 才能完成这些过程。

注意

以下说明中的某些 Visual Studio 用户界面元素在计算机上出现的名称或位置可能会不同。 这些元素取决于你所使用的 Visual Studio 版本和你所使用的设置。 有关详细信息,请参阅个性化设置 IDE

创建新的控制台应用程序

启动 Visual Studio。 在 “文件” 菜单上,指向 “新建”,然后选择 “项目”。 在“模板类别”窗格中,展开“C#”,然后选择“Windows”。 查看“模板”窗格的顶部,确保“.NET Framework 4”出现在“目标框架”框中。 在“模板”窗格中,选择“控制台应用程序”。 在“名称”字段中键入项目的名称。 选择“确定”。 新项目将出现在“解决方案资源管理器”中。

添加引用

在“解决方案资源管理器”中,右键单击你的项目名称,然后选择“添加引用”。 此时会显示“添加引用”对话框。 在“.NET”页上的“组件名称”列表中,选择“Microsoft.Office.Interop.Word” 。 选择“确定”。

添加必要的 using 指令

在“解决方案资源管理器”中,右键单击“Program.cs”文件,然后选择“查看代码”。 将以下 using 指令添加到代码文件的顶部:

using Word = Microsoft.Office.Interop.Word;

在 Word 文档中显示文本

在“Program.cs”的 Program 类中,添加以下方法以创建 Word 应用程序和 Word 文档。 Add 方法具有四个可选参数。 此示例使用这些参数的默认值。 因此,调用语句中不必有参数。

static void DisplayInWord()
{
    var wordApp = new Word.Application();
    wordApp.Visible = true;
    // docs is a collection of all the Document objects currently
    // open in Word.
    Word.Documents docs = wordApp.Documents;

    // Add a document to the collection and name it doc.
    Word.Document doc = docs.Add();
}

将以下代码添加到方法的末尾,以定义要在文档何处显示文本,以及要显示什么文本:

// Define a range, a contiguous area in the document, by specifying
// a starting and ending character position. Currently, the document
// is empty.
Word.Range range = doc.Range(0, 0);

// Use the InsertAfter method to insert a string at the end of the
// current range.
range.InsertAfter("Testing, testing, testing. . .");

运行应用程序

将以下语句添加到 Main:

DisplayInWord();

Ctrl+F5 运行项目。 此时会出现一个 Word 文档,其中包含指定的文本。

将文本更改为表

使用 ConvertToTable 方法将文本放入表中。 该方法具有 16 个可选参数。 IntelliSense 将可选参数放入括号中,如下图所示。

List of parameters for ConvertToTable method

通过使用命名实参和可选实参,可以只对要更改的形参指定值。 将以下代码添加到方法 DisplayInWord 的末尾以创建一个表。 此参数指定 range 中文本字符串内的逗号分隔表的各个单元格。

// Convert to a simple table. The table will have a single row with
// three columns.
range.ConvertToTable(Separator: ",");

Ctrl+F5 运行项目。

使用其他参数进行试验

更改表以使其具有一列三行,将 DisplayInWord 中的最后一行替换为以下语句,然后按 CTRL+F5

range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);

为表指定预定义的格式,将 DisplayInWord 中的最后一行替换为以下语句,然后按 CTRL+F5。 格式可以为任何 WdTableFormat 常量。

range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
    Format: Word.WdTableFormat.wdTableFormatElegant);

示例

下面的代码包括完整的示例:

using System;
using Word = Microsoft.Office.Interop.Word;

namespace OfficeHowTo
{
    class WordProgram
    {
        static void Main(string[] args)
        {
            DisplayInWord();
        }

        static void DisplayInWord()
        {
            var wordApp = new Word.Application();
            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            Word.Document doc = docs.Add();

            // Define a range, a contiguous area in the document, by specifying
            // a starting and ending character position. Currently, the document
            // is empty.
            Word.Range range = doc.Range(0, 0);

            // Use the InsertAfter method to insert a string at the end of the
            // current range.
            range.InsertAfter("Testing, testing, testing. . .");

            // You can comment out any or all of the following statements to
            // see the effect of each one in the Word document.

            // Next, use the ConvertToTable method to put the text into a table.
            // The method has 16 optional parameters. You only have to specify
            // values for those you want to change.

            // Convert to a simple table. The table will have a single row with
            // three columns.
            range.ConvertToTable(Separator: ",");

            // Change to a single column with three rows..
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);

            // Format the table.
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
                Format: Word.WdTableFormat.wdTableFormatElegant);
        }
    }
}