如何存取 Office Interop 物件

C# 的功能可簡化 Office API 物件的存取。 新功能包括具名引數和選擇性引數、稱為 dynamic 的新類型,以及傳遞引數以像是實值參數的形式,參考 COM 方法中參數的能力。

在本文章中,您將使用新的功能撰寫可建立及顯示 Microsoft Office Excel 工作表的程式碼。 您將要撰寫可加入 Office Word 文件的程式碼,而該文件包含連結至 Excel 工作表的圖示。

若要完成這個逐步解說,電腦上必須安裝 Microsoft Office Excel 2007 和 Microsoft Office Word 2007 或更新版本。

注意

在下列指示的某些 Visual Studio 使用者介面項目中,您的電腦可能會顯示不同的名稱或位置: 您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。 如需詳細資訊,請參閱將 Visual Studio IDE 個人化

重要

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 增益集的伺服器端。

建立新的主控台應用程式

  1. 啟動 Visual Studio。
  2. 在 [檔案] 功能表上,指向 [新增],然後選取 [專案]。 [新增專案] 對話方塊隨即出現。
  3. 在 [安裝的範本] 窗格中,展開 [C#],然後選取 [Windows]
  4. 查看 [新增專案] 對話方塊頂端,確定選取 [.NET Framework 4] (或更新版本) 作為目標架構。
  5. 在 [範本] 窗格中,選取 [主控台應用程式]
  6. 在 [名稱] 欄位中鍵入專案的名稱。
  7. 選取 [確定]。

新的專案隨即會出現在方案總管中。

加入參考

  1. 在 [方案總管] 中,於專案名稱上按一下滑鼠右鍵,然後選取 [新增參考]。 [新增參考] 對話方塊隨即出現。
  2. 在 [組件] 頁面的 [元件名稱] 清單中,選取 [Microsoft.Office.Interop.Word],然後按住 CTRL 鍵並選取 [Microsoft.Office.Interop.Excel]。 如果您未看到組件,您可能必須加以安裝。 請參閱如何:安裝 Office 主要 Interop 組件
  3. 選取 [確定]。

加入必要的 using 指示詞

在 [方案總管]中,以滑鼠右鍵按一下 Program.cs 檔案,然後選取 [檢視程式碼]。 將下列 using 指示詞加入程式碼檔案頂端:

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

建立銀行帳戶清單

將下列類別定義貼入 Program 類別下的 Program.cs

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

將下列程式碼加入 Main 方法,以建立含有兩個帳戶的 bankAccounts 清單。

// 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 的方法

  1. 將下列方法加入 Program 類別,以設定 Excel 試算表。 Add 方法有用以指定特定範本的選擇性參數。 如果您想要使用參數的預設值,則可利用選擇性參數省略該參數的引數。 由於您未提供引數,因此 Add 會使用預設範本並建立新的活頁簿。 舊版 C# 中對等的陳述式需要有預留位置引數: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 particular 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;
}

DisplayInExcel 結尾,加入下列程式碼。 程式碼會將值插入工作表第一個資料列的前兩個資料行。

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

DisplayInExcel 結尾,加入下列程式碼。 foreach 迴圈會將帳戶清單中的資訊,放入工作表連續資料列的前兩個資料行。


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

DisplayInExcel 結尾加入下列程式碼,以調整資料行寬度以容納內容。

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

因為 ExcelApp.Columns[1] 會傳回 Object,所以舊版 C# 需要明確轉換這些作業,而 AutoFit 是 Excel Range 方法。 下列各行會顯示轉型。

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

如果 EmbedInteropTypes 編譯器選項參考組件;或者,同樣地,如果 Excel Embed Interop Types 屬性為 true,則 C# 會自動將傳回的 Object 轉換為 dynamic。 這個屬性的預設值為 True。

執行專案

Main 結尾,加入下行。

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

按下 CTRL+F5。 隨即會出現內含兩個帳戶資料的 Excel 工作表。

加入 Word 文件

下列程式碼會開啟 Word 應用程式,並建立連結至 Excel 工作表的圖示。 將本步驟稍後提供的 CreateIconInWordDoc 方法,貼入 Program 類別。 CreateIconInWordDoc 使用具名和選擇性引數來降低 AddPasteSpecial 方法呼叫的複雜性。 這些呼叫採用兩個其他新功能,簡化了具有參考參數的 COM 方法呼叫。 首先,您可以將引數以實值參數的形式傳送到參考參數。 也就是說,可以直接傳送值而無須建立每個參考參數的變數。 編譯器會產生暫存變數來保存引數值,並在從呼叫返回時捨棄變數。 其次,您可以省略引數清單中的 ref 關鍵字。

Add 方法有四個參考參數,而且都是選擇性參數。 如果想要使用其預設值,可以省略任何或所有參數的引數。

PasteSpecial 方法會將內容插入剪貼簿。 此方法有七個參考參數,且都是選擇性參數。 下列程式碼指定其中兩個的引數:Link 可建立剪貼簿的內容的來源連結,以及 DisplayAsIcon 可將連結顯示為圖示。 可以為這兩個引數使用具名引數,並省略其他引數。 雖然這些引數是參考參數,但是您不需要使用 ref 關鍵字,或建立傳送為引數的變數。 可以直接傳送值。

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);
}

Main 結尾,加入下列陳述式。

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

DisplayInExcel 結尾,加入下列陳述式。 Copy 方法會將工作表加入剪貼簿。

// 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();

按下 CTRL+F5。 隨即會出現含有圖示的 Word 文件。 按兩下圖示,即可將該工作表帶到前景。

設定內嵌 Interop 類型屬性

當您在執行階段呼叫不需要主要 Interop 組件 (PIA) 的 COM 類型時,可以使用其他增強功能。 移除與 PIA 的相依性,可達成版本獨立且更容易進行部署。 如需沒有 PIA 的程式設計優點的詳細資訊,請參閱逐步解說:從 Managed 組件內嵌類型

此外,由於 dynamic 型別代表 COM 方法中宣告的必要和傳回型別,因此讓程式設計更容易。 除非處於執行階段,否則不會評估類型為 dynamic 的變數,如此即無須明確轉型。 如需詳細資訊,請參閱使用動態類型

預設行為是內嵌類型資訊,而非使用 PIA。 由於該行為,已簡化數個先前的範例。 您不需要任何明確轉型。 例如,worksheet 中的 DisplayInExcel 宣告,撰寫為 Excel._Worksheet workSheet = excelApp.ActiveSheet,而非 Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet。 如果沒有預設值,則相同方法中的 AutoFit 呼叫也需要明確轉型,因為 ExcelApp.Columns[1] 會傳回 Object,而 AutoFit 是 Excel 方法。 下列程式碼會顯示轉型。

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

若要變更預設值,並使用 PIA 而非內嵌類型資訊,請展開 [方案總管] 中的 [參考] 節點,然後選取 [Microsoft.Office.Interop.Excel] 或 [Microsoft.Office.Interop.Word]。 如果看不到 [屬性] 視窗,請按 F4 鍵。 在屬性清單中尋找 [內嵌 Interop 類型],並將其值變更為 False。 同樣地,也可以在命令提示字元處使用 References 編譯器選項,而非 EmbedInteropTypes 進行編譯。

加入表格的其他格式

AutoFit 中對兩個 DisplayInExcel 的呼叫,取代為下列陳述式。

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

這個方法 AutoFormat 有七個值參數,全部都是選擇性參數。 您可利用具名引數和選擇性引數,提供零個引數、數個引數或所有引數。 在前述陳述式中,只為其中一個參數 (Format) 提供引數。 因為 Format 是參數清單中的第一個參數,所以無須提供參數名稱。 但如果包含參數名稱,則可能較容易了解該陳述式,如下列程式碼所示。

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

按 CTRL + F5 鍵查看結果。 您可在 XlRangeAutoFormat 列舉的清單中其他格式。

範例

下列程式碼顯示完整範例。

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

namespace OfficeProgrammingWalkthruComplete
{
    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 particular 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; }
    }
}

另請參閱