如何:使用 Visual C# 功能存取 Office Interop 物件 (C# 程式設計指南)How to: Access Office Interop Objects by Using Visual C# Features (C# Programming Guide)

Visual C# 的功能可以簡化 Office API 物件存取。Visual C# has features that simplify access to Office API objects. 新功能包括具名引數和選擇性引數、稱為 dynamic 的新類型,以及傳遞引數以像是實值參數的形式,參考 COM 方法中參數的能力。The new features include named and optional arguments, a new type called dynamic, and the ability to pass arguments to reference parameters in COM methods as if they were value parameters.

在本主題中,您將使用新的功能撰寫可建立及顯示 Microsoft Office Excel 工作表的程式碼。In this topic you will use the new features to write code that creates and displays a Microsoft Office Excel worksheet. 接著,您將要撰寫可加入 Office Word 文件的程式碼,而該文件包含連結至 Excel 工作表的圖示。You will then write code to add an Office Word document that contains an icon that is linked to the Excel worksheet.

若要完成這個逐步解說,電腦上必須安裝 Microsoft Office Excel 2007 和 Microsoft Office Word 2007 或更新版本。To complete this walkthrough, you must have Microsoft Office Excel 2007 and Microsoft Office Word 2007, or later versions, installed on your computer.

如果您使用 Windows VistaWindows Vista 以前的作業系統,請確定已安裝 .NET Framework 2.0.NET Framework 2.0If you are using an operating system that is older than Windows VistaWindows Vista, make sure that .NET Framework 2.0.NET Framework 2.0 is installed.

注意

在下列指示的某些 Visual Studio 使用者介面項目中,您的電腦可能會顯示不同的名稱或位置:Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. 您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。The Visual Studio edition that you have and the settings that you use determine these elements. 如需詳細資訊,請參閱將 Visual Studio IDE 個人化For more information, see Personalizing the IDE.

建立新的主控台應用程式To create a new console application

  1. 啟動 Visual Studio。Start Visual Studio.

  2. 在 [檔案] 功能表中,指向 [新增] ,然後按一下 [專案] 。On the File menu, point to New, and then click Project. [ 新增專案 ] 對話方塊隨即出現。The New Project dialog box appears.

  3. 在 [已安裝的範本] 窗格中,展開 [Visual C#],然後按一下 [Windows]。In the Installed Templates pane, expand Visual C#, and then click Windows.

  4. 查看 [新增專案] 對話方塊頂端,確定已選取 .NET Framework 4 作為目標架構。Look at the top of the New Project dialog box to make sure that .NET Framework 4 (or later version) is selected as a target framework.

  5. 按一下 [範本] 窗格中的 [主控台應用程式]。In the Templates pane, click Console Application.

  6. 在 [名稱] 欄位中鍵入專案的名稱。Type a name for your project in the Name field.

  7. 按一下 [確定 Deploying Office Solutions]。Click OK.

    新的專案隨即會出現在方案總管中。The new project appears in Solution Explorer.

加入參考To add references

  1. 在方案總管中,於專案名稱上按一下滑鼠右鍵,然後按一下 [新增參考]。In Solution Explorer, right-click your project's name and then click Add Reference. [加入參考] 對話方塊隨即出現。The Add Reference dialog box appears.

  2. 在 [組件] 頁面的 [元件名稱] 清單中,選取 [Microsoft.Office.Interop.Word],然後按住 CTRL 鍵並選取 [Microsoft.Office.Interop.Excel]。On the Assemblies page, select Microsoft.Office.Interop.Word in the Component Name list, and then hold down the CTRL key and select Microsoft.Office.Interop.Excel. 如果看不到組件,則可能需要確定它們已安裝並已顯示 (請參閱如何:安裝 Office 主要 Interop 組件)。If you do not see the assemblies, you may need to ensure they are installed and displayed (see How to: Install Office Primary Interop Assemblies)

  3. 按一下 [確定 Deploying Office Solutions]。Click OK.

加入必要的 using 指示詞To add necessary using directives

  1. 在方案總管中,以滑鼠右鍵按一下 Program.cs 檔案,然後按一下 [檢視程式碼]。In Solution Explorer, right-click the Program.cs file and then click View Code.

  2. 將下列 using 指示詞加入程式碼檔案頂端。Add the following using directives to the top of the code file.

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

建立銀行帳戶清單To create a list of bank accounts

  1. 將下列類別定義貼入 Program 類別下的 Program.csPaste the following class definition into Program.cs, under the Program class.

    public class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
    }
    
  2. 將下列程式碼加入 Main 方法,以建立含有兩個帳戶的 bankAccounts 清單。Add the following code to the Main method to create a bankAccounts list that contains two accounts.

    // Create a list of accounts.
    var bankAccounts = new List<Account> {
        new Account { 
                      ID = 345678,
                      Balance = 541.27
                    },
        new Account {
                      ID = 1230221,
                      Balance = -127.44
                    }
    };
    

宣告將帳戶資訊匯出至 Excel 的方法To declare a method that exports account information to Excel

  1. 將下列方法加入 Program 類別,以設定 Excel 試算表。Add the following method to the Program class to set up an Excel worksheet.

    新增方法具有指定特定範本的選擇性參數。Method Add has an optional parameter for specifying a particular template. 如果您想要使用參數的預設值,則可利用選擇性參數 (C# 4C# 4 中的新功能) 省略該參數的引數。Optional parameters, new in C# 4C# 4, enable you to omit the argument for that parameter if you want to use the parameter's default value. 因為下列程式碼中未傳送引數,所以 Add 使用預設範本並建立新的活頁簿。Because no argument is sent in the following code, Add uses the default template and creates a new workbook. 舊版 C# 中對等的陳述式需要有預留位置引數:ExcelApp.Workbooks.Add(Type.Missing)The equivalent statement in earlier versions of C# requires a placeholder argument: ExcelApp.Workbooks.Add(Type.Missing).

    static void DisplayInExcel(IEnumerable<Account> accounts)
    {
        var excelApp = new Excel.Application();
        // Make the object visible.
        excelApp.Visible = true;
    
        // Create a new, empty workbook and add it to the collection returned 
        // by property Workbooks. The new workbook becomes the active workbook.
        // Add has an optional parameter for specifying a praticular template. 
        // Because no argument is sent in this example, Add creates a new workbook. 
        excelApp.Workbooks.Add();
    
        // This example uses a single workSheet. The explicit type casting is
        // removed in a later procedure.
        Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
    }
    
  2. DisplayInExcel 結尾,加入下列程式碼。Add the following code at the end of DisplayInExcel. 程式碼會將值插入工作表第一個資料列的前兩個資料行。The code inserts values into the first two columns of the first row of the worksheet.

    // Establish column headings in cells A1 and B1.
    workSheet.Cells[1, "A"] = "ID Number";
    workSheet.Cells[1, "B"] = "Current Balance";
    
  3. DisplayInExcel 結尾,加入下列程式碼。Add the following code at the end of DisplayInExcel. foreach 迴圈會將帳戶清單中的資訊,放入工作表連續資料列的前兩個資料行。The foreach loop puts the information from the list of accounts into the first two columns of successive rows of the worksheet.

    
    var row = 1;
    foreach (var acct in accounts)
    {
        row++;
        workSheet.Cells[row, "A"] = acct.ID;
        workSheet.Cells[row, "B"] = acct.Balance;
    }
    
  4. DisplayInExcel 結尾加入下列程式碼,以調整資料行寬度以容納內容。Add the following code at the end of DisplayInExcel to adjust the column widths to fit the content.

    workSheet.Columns[1].AutoFit();
    workSheet.Columns[2].AutoFit();
    

    舊版 C# 需要明確轉換這些作業,因為 ExcelApp.Columns[1] 會傳回 Object,而 AutoFit 是 Excel Range 方法。Earlier versions of C# require explicit casting for these operations because ExcelApp.Columns[1] returns an Object, and AutoFit is an Excel Range method. 下列各行會顯示轉型。The following lines show the casting.

    ((Excel.Range)workSheet.Columns[1]).AutoFit();
    ((Excel.Range)workSheet.Columns[2]).AutoFit();
    

    如果 /link 編譯器選項參考組件;或者,同樣地,如果 Excel 內嵌 Interop 類型屬性設定為 true,則 C# 4C# 4 和更新版本會自動將傳回的 Object 轉換為 dynamicC# 4C# 4, and later versions, converts the returned Object to dynamic automatically if the assembly is referenced by the /link compiler option or, equivalently, if the Excel Embed Interop Types property is set to true. 這個屬性的預設值為 True。True is the default value for this property.

執行專案To run the project

  1. Main 結尾,加入下行。Add the following line at the end of Main.

    // Display the list in an Excel spreadsheet.
    DisplayInExcel(bankAccounts);
    
  2. 按下 CTRL+F5。Press CTRL+F5.

    隨即會出現內含兩個帳戶資料的 Excel 工作表。An Excel worksheet appears that contains the data from the two accounts.

加入 Word 文件To add a Word document

  1. 為了說明 C# 4C# 4 和更新版本中加強 Office 程式設計的其他方法,下列程式碼會開啟 Word 應用程式,並建立 Excel 工作表連結的圖示。To illustrate additional ways in which C# 4C# 4, and later versions, enhances Office programming, the following code opens a Word application and creates an icon that links to the Excel worksheet.

    將本步驟稍後提供的 CreateIconInWordDoc 方法,貼入 Program 類別。Paste method CreateIconInWordDoc, provided later in this step, into the Program class. CreateIconInWordDoc 使用具名和選擇性引數來降低 Documents.AddSelection.PasteSpecial 方法呼叫的複雜性。CreateIconInWordDoc uses named and optional arguments to reduce the complexity of the method calls to Add and PasteSpecial. 這些呼叫採用 C# 4C# 4 引進的兩個其他新功能,簡化了具有參考參數之 COM 方法的呼叫。These calls incorporate two other new features introduced in C# 4C# 4 that simplify calls to COM methods that have reference parameters. 首先,您可以將引數以實值參數的形式傳送到參考參數。First, you can send arguments to the reference parameters as if they were value parameters. 也就是說,可以直接傳送值而無須建立每個參考參數的變數。That is, you can send values directly, without creating a variable for each reference parameter. 編譯器會產生暫存變數來保存引數值,並在從呼叫返回時捨棄變數。The compiler generates temporary variables to hold the argument values, and discards the variables when you return from the call. 其次,您可以省略引數清單中的 ref 關鍵字。Second, you can omit the ref keyword in the argument list.

    Add 方法有四個參考參數,而且都是選擇性參數。The Add method has four reference parameters, all of which are optional. C# 4C# 4 或更新版本中,如果想要使用其預設值,可以省略任何或所有參數的引數。In C# 4C# 4, or later versions, you can omit arguments for any or all of the parameters if you want to use their default values. Visual C# 2008Visual C# 2008 和舊版本中,必須為每個參數提供引數,且引數必須是變數,因為參數是參考參數。In Visual C# 2008Visual C# 2008 and earlier versions, an argument must be provided for each parameter, and the argument must be a variable because the parameters are reference parameters.

    PasteSpecial 方法會將內容插入剪貼簿。The PasteSpecial method inserts the contents of the Clipboard. 此方法有七個參考參數,且都是選擇性參數。The method has seven reference parameters, all of which are optional. 下列程式碼指定其中兩個的引數:Link 可建立剪貼簿的內容的來源連結,以及 DisplayAsIcon 可將連結顯示為圖示。The following code specifies arguments for two of them: Link, to create a link to the source of the Clipboard contents, and DisplayAsIcon, to display the link as an icon. C# 4C# 4 中,可以為這兩者使用具名引數,並省略其他引數。In C# 4C# 4, you can use named arguments for those two and omit the others. 雖然這些是參考參數,但是您不需要使用 ref 關鍵字,或建立傳送為引數的變數。Although these are reference parameters, you do not have to use the ref keyword, or to create variables to send in as arguments. 可以直接傳送值。You can send the values directly. Visual C# 2008Visual C# 2008 和舊版本中,必須為每個參考參數傳送變數引數。In Visual C# 2008Visual C# 2008 and earlier versions, you must send a variable argument for each reference parameter.

    static void CreateIconInWordDoc()
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
    
        // The Add method has four reference parameters, all of which are 
        // optional. Visual C# allows you to omit arguments for them if
        // the default values are what you want.
        wordApp.Documents.Add();
    
        // PasteSpecial has seven reference parameters, all of which are 
        // optional. This example uses named arguments to specify values 
        // for two of the parameters. Although these are reference 
        // parameters, you do not need to use the ref keyword, or to create 
        // variables to send in as arguments. You can send the values directly.
        wordApp.Selection.PasteSpecial( Link: true, DisplayAsIcon: true);
    }
    

    Visual C# 2008Visual C# 2008 或舊版語言中,需要有下列更為複雜的程式碼。In Visual C# 2008Visual C# 2008 or earlier versions of the language, the following more complex code is required.

    static void CreateIconInWordDoc2008()
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
    
        // The Add method has four parameters, all of which are optional. 
        // In Visual C# 2008 and earlier versions, an argument has to be sent 
        // for every parameter. Because the parameters are reference  
        // parameters of type object, you have to create an object variable
        // for the arguments that represents 'no value'. 
    
        object useDefaultValue = Type.Missing;
    
        wordApp.Documents.Add(ref useDefaultValue, ref useDefaultValue,
            ref useDefaultValue, ref useDefaultValue);
    
        // PasteSpecial has seven reference parameters, all of which are
        // optional. In this example, only two of the parameters require
        // specified values, but in Visual C# 2008 an argument must be sent
        // for each parameter. Because the parameters are reference parameters,
        // you have to contruct variables for the arguments.
        object link = true;
        object displayAsIcon = true;
    
        wordApp.Selection.PasteSpecial( ref useDefaultValue,
                                        ref link,
                                        ref useDefaultValue,
                                        ref displayAsIcon,
                                        ref useDefaultValue,
                                        ref useDefaultValue,
                                        ref useDefaultValue);
    }
    
  2. Main 結尾,加入下列陳述式。Add the following statement at the end of Main.

    // Create a Word document that contains an icon that links to
    // the spreadsheet.
    CreateIconInWordDoc();
    
  3. DisplayInExcel 結尾,加入下列陳述式。Add the following statement at the end of DisplayInExcel. Copy 方法會將工作表加入剪貼簿。The Copy method adds the worksheet to the Clipboard.

    // Put the spreadsheet contents on the clipboard. The Copy method has one
    // optional parameter for specifying a destination. Because no argument  
    // is sent, the destination is the Clipboard.
    workSheet.Range["A1:B3"].Copy();
    
  4. 按下 CTRL+F5。Press CTRL+F5.

    隨即會出現含有圖示的 Word 文件。A Word document appears that contains an icon. 按兩下圖示,即可將該工作表帶到前景。Double-click the icon to bring the worksheet to the foreground.

設定內嵌 Interop 類型屬性To set the Embed Interop Types property

  1. 當您在執行階段呼叫不需要主要 Interop 組件 (PIA) 的 COM 類型時,可以使用其他增強功能。Additional enhancements are possible when you call a COM type that does not require a primary interop assembly (PIA) at run time. 移除與 PIA 的相依性,可達成版本獨立且更容易進行部署。Removing the dependency on PIAs results in version independence and easier deployment. 如需沒有 PIA 的程式設計優點的詳細資訊,請參閱逐步解說:從 Managed 組件內嵌類型For more information about the advantages of programming without PIAs, see Walkthrough: Embedding Types from Managed Assemblies.

    此外,程式設計會更為容易,因為 COM 方法所需和所傳回的類型可以使用類型 dynamic 而非 Object 加以呈現。In addition, programming is easier because the types that are required and returned by COM methods can be represented by using the type dynamic instead of Object. 除非處於執行階段,否則不會評估類型為 dynamic 的變數,如此即無須明確轉型。Variables that have type dynamic are not evaluated until run time, which eliminates the need for explicit casting. 如需詳細資訊,請參閱使用動態類型For more information, see Using Type dynamic.

    C# 4C# 4 中,預設行為是內嵌類型資訊,而非使用 PIA。In C# 4C# 4, embedding type information instead of using PIAs is default behavior. 因為使用該預設值,已簡化了數個先前的範例,因為明確轉型已非必要。Because of that default, several of the previous examples are simplified because explicit casting is not required. 例如,worksheet 中的 DisplayInExcel 宣告,撰寫為 Excel._Worksheet workSheet = excelApp.ActiveSheet,而非 Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheetFor example, the declaration of worksheet in DisplayInExcel is written as Excel._Worksheet workSheet = excelApp.ActiveSheet rather than Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet. 如果沒有預設值,則相同方法中的 AutoFit 呼叫也需要明確轉型,因為 ExcelApp.Columns[1] 會傳回 Object,而 AutoFit 是 Excel 方法。The calls to AutoFit in the same method also would require explicit casting without the default, because ExcelApp.Columns[1] returns an Object, and AutoFit is an Excel method. 下列程式碼會顯示轉型。The following code shows the casting.

    ((Excel.Range)workSheet.Columns[1]).AutoFit();
    ((Excel.Range)workSheet.Columns[2]).AutoFit();
    
  2. 若要變更預設值,並使用 PIA 而非內嵌類型資訊,請展開方案總管中的 [參考] 節點,然後選取 Microsoft.Office.Interop.ExcelMicrosoft.Office.Interop.WordTo change the default and use PIAs instead of embedding type information, expand the References node in Solution Explorer and then select Microsoft.Office.Interop.Excel or Microsoft.Office.Interop.Word.

  3. 如果看不到 [屬性] 視窗,請按 F4 鍵。If you cannot see the Properties window, press F4.

  4. 在屬性清單中尋找 [內嵌 Interop 類型],並將其值變更為 FalseFind Embed Interop Types in the list of properties, and change its value to False. 同樣地,也可以在命令提示字元處使用 /reference 編譯器選項,而非 /link 進行編譯。Equivalently, you can compile by using the /reference compiler option instead of /link at a command prompt.

加入表格的其他格式To add additional formatting to the table

  1. AutoFit 中對兩個 DisplayInExcel 的呼叫,取代為下列陳述式。Replace the two calls to AutoFit in DisplayInExcel with the following statement.

    // Call to AutoFormat in Visual C# 2010.
    workSheet.Range["A1", "B3"].AutoFormat(
        Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);
    

    Range.AutoFormat 方法有七個實值參數,都是選擇性參數。The AutoFormat method has seven value parameters, all of which are optional. 您可利用具名引數和選擇性引數,提供零個引數、數個引數或所有引數。Named and optional arguments enable you to provide arguments for none, some, or all of them. 在前述陳述式中,只為其中一個參數 (Format) 提供引數。In the previous statement, an argument is supplied for only one of the parameters, Format. 因為 Format 是參數清單中的第一個參數,所以無須提供參數名稱。Because Format is the first parameter in the parameter list, you do not have to provide the parameter name. 但如果包含參數名稱,則可能較容易了解該陳述式,如下列程式碼所示。However, the statement might be easier to understand if the parameter name is included, as is shown in the following code.

    // Call to AutoFormat in Visual C# 2010.
    workSheet.Range["A1", "B3"].AutoFormat(Format:
        Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);
    
  2. 按 CTRL + F5 鍵查看結果。Press CTRL+F5 to see the result. 其他格式會列在 XlRangeAutoFormat 列舉中。Other formats are listed in the XlRangeAutoFormat enumeration.

  3. 請比較步驟 1 中的陳述式與下列程式碼,這樣會顯示 Visual C# 2008Visual C# 2008 或舊版本中所需的引數。Compare the statement in step 1 with the following code, which shows the arguments that are required in Visual C# 2008Visual C# 2008 or earlier versions.

    // The AutoFormat method has seven optional value parameters. The
    // following call specifies a value for the first parameter, and uses 
    // the default values for the other six. 
    
    // Call to AutoFormat in Visual C# 2008. This code is not part of the
    // current solution.
    excelApp.get_Range("A1", "B4").AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatTable3, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing);
    

範例Example

下列程式碼顯示完整範例。The following code shows the complete example.

using System;
using System.Collections.Generic;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;


namespace OfficeProgramminWalkthruComplete
{
    class Walkthrough
    {
        static void Main(string[] args)
        {
            // Create a list of accounts.
            var bankAccounts = new List<Account> 
            {
                new Account { 
                              ID = 345678,
                              Balance = 541.27
                            },
                new Account {
                              ID = 1230221,
                              Balance = -127.44
                            }
            };

            // Display the list in an Excel spreadsheet.
            DisplayInExcel(bankAccounts);

            // Create a Word document that contains an icon that links to
            // the spreadsheet.
            CreateIconInWordDoc();
        }

        static void DisplayInExcel(IEnumerable<Account> accounts)
        {
            var excelApp = new Excel.Application();
            // Make the object visible.
            excelApp.Visible = true;

            // Create a new, empty workbook and add it to the collection returned 
            // by property Workbooks. The new workbook becomes the active workbook.
            // Add has an optional parameter for specifying a praticular template. 
            // Because no argument is sent in this example, Add creates a new workbook. 
            excelApp.Workbooks.Add();

            // This example uses a single workSheet. 
            Excel._Worksheet workSheet = excelApp.ActiveSheet;

            // Earlier versions of C# require explicit casting.
            //Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

            // Establish column headings in cells A1 and B1.
            workSheet.Cells[1, "A"] = "ID Number";
            workSheet.Cells[1, "B"] = "Current Balance";

            var row = 1;
            foreach (var acct in accounts)
            {
                row++;
                workSheet.Cells[row, "A"] = acct.ID;
                workSheet.Cells[row, "B"] = acct.Balance;
            }

            workSheet.Columns[1].AutoFit();
            workSheet.Columns[2].AutoFit();

            // Call to AutoFormat in Visual C#. This statement replaces the 
            // two calls to AutoFit.
            workSheet.Range["A1", "B3"].AutoFormat(
                Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);

            // Put the spreadsheet contents on the clipboard. The Copy method has one
            // optional parameter for specifying a destination. Because no argument  
            // is sent, the destination is the Clipboard.
            workSheet.Range["A1:B3"].Copy();
        }

        static void CreateIconInWordDoc()
        {
            var wordApp = new Word.Application();
            wordApp.Visible = true;

            // The Add method has four reference parameters, all of which are 
            // optional. Visual C# allows you to omit arguments for them if
            // the default values are what you want.
            wordApp.Documents.Add();

            // PasteSpecial has seven reference parameters, all of which are 
            // optional. This example uses named arguments to specify values 
            // for two of the parameters. Although these are reference 
            // parameters, you do not need to use the ref keyword, or to create 
            // variables to send in as arguments. You can send the values directly.
            wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);
        }
    }

    public class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
    }
}

請參閱See Also

Type.Missing
dynamicdynamic
使用動態型別Using Type dynamic
具名和選擇性引數Named and Optional Arguments
如何:在 Office 程式設計中使用具名和選擇性引數How to: Use Named and Optional Arguments in Office Programming