オフィスインターオプオブジェクトへのアクセス方法 – C#

この記事では、C#を使用してMicrosoft Office APIオブジェクトへのアクセスを簡素化する新機能について説明しています。主な機能には、名前付きおよびオプション引数、新しい動的型、およびCOMメソッドの参照パラメーターに値パラメーターのように引数を渡す能力が含まれています。具体的には、Excelワークシートを作成し、Office Wordドキュメントにそのワークシートへのリンクアイコンを追加する手順が示されています。これを実行するには、Microsoft Office Excel 2007およびMicrosoft Office Word 2007以上のバージョンが必要です。

C#を使ったMicrosoft Officeのプログラミングガイド

C#には、Office APIオブジェクトへのアクセスを簡素化する機能が搭載されています。新機能には、名前付きおよびオプションの引数、新しい型であるdynamic、そしてCOMメソッドの参照パラメーターに値パラメーターのように引数を渡す能力が含まれます。

この記事では、これらの新機能を利用して、Microsoft Office Excelのワークシートを作成し表示するコードを書きます。また、Excelのワークシートにリンクされたアイコンを含むOffice Wordドキュメントを追加するコードも作成します。

前提条件

この手順を完了するためには、Microsoft Office Excel 2007およびMicrosoft Office Word 2007以降のバージョンがコンピューターにインストールされている必要があります。

注意事項

コンピューターによっては、以下の手順に示すVisual Studioのユーザーインターフェース要素の名前や場所が異なる場合があります。使用しているVisual Studioのエディションや設定によってこれらは変わります。詳細については、IDEの個人化を参照してください。

重要事項

VSTO (Visual Studio Tools for Office)は、.NET Frameworkに依存しています。COMアドインも.NET Frameworkを使用して作成できますが、Officeアドインは.NET Coreや.NET 5+を使用して作成することはできません。これは、.NET Coreや.NET 5+が.NET Frameworkと同じプロセスで動作できず、アドインの読み込み失敗を引き起こす可能性があるためです。VSTOおよびCOMアドインのプラットフォームは、.NET Coreまたは.NET 5+での使用を更新する予定はありません。これらの技術の最新バージョンであるASP.NET Coreを使用して、Office Web Add-insのサーバー側を作成できます。

新しいコンソールアプリケーションを作成する手順

  1. Visual Studioを起動します。
  2. ファイルメニューから新規作成を選択し、次にプロジェクトを選択します。新規プロジェクトダイアログボックスが表示されます。
  3. インストールされたテンプレートペインで、C#を展開し、Windowsを選択します。
  4. 新規プロジェクトダイアログボックスの上部で、ターゲットフレームワークとして.NET Framework 4(またはそれ以降のバージョン)が選択されていることを確認します。
  5. テンプレートペインで、コンソールアプリケーションを選択します。
  6. 名前フィールドにプロジェクト名を入力します。
  7. OKを選択します。

新しいプロジェクトがソリューションエクスプローラーに表示されます。

参照を追加する手順

  1. ソリューションエクスプローラーでプロジェクト名を右クリックし、参照の追加を選択します。参照の追加ダイアログボックスが表示されます。
  2. アセンブリページで、Component NameリストからMicrosoft.Office.Interop.Wordを選択し、CTRLキーを押しながらMicrosoft.Office.Interop.Excelを選択します。アセンブリが表示されない場合は、インストールが必要な場合があります。詳細は、Office Primary Interop Assembliesのインストール方法を参照してください。
  3. OKを選択します。

必要なusingディレクティブを追加する手順

ソリューションエクスプローラーProgram.csファイルを右クリックし、コードの表示を選択します。コードファイルの先頭に次のusingディレクティブを追加します。

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

銀行口座のリストを作成する手順

次のクラス定義をProgram.csProgramクラスの下に貼り付けます。

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

次に、Mainメソッドに次のコードを追加して、bankAccountsリストを作成します。

// アカウントのリストを作成する。
var bankAccounts = new List<Account> {
    new Account {
                  ID = 345678,
                  Balance = 541.27
                },
    new Account {
                  ID = 1230221,
                  Balance = -127.44
                }
};

アカウント情報をExcelにエクスポートするメソッドを宣言する手順

Programクラスに次のメソッドを追加して、Excelワークシートをセットアップします。

static void DisplayInExcel(IEnumerable<Account> accounts)
{
    var excelApp = new Excel.Application();
    excelApp.Visible = true;
    excelApp.Workbooks.Add();

    Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

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

プロジェクトを実行する手順

Mainの最後に次の行を追加します。

// 銀行口座のリストをExcelスプレッドシートに表示。
DisplayInExcel(bankAccounts);

CTRL+F5を押すと、2つのアカウントからのデータを含むExcelワークシートが表示されます。

Wordドキュメントを追加する手順

次のコードは、Wordアプリケーションを開き、Excelワークシートにリンクされたアイコンを作成します。メソッドCreateIconInWordDocProgramクラスに追加します。

static void CreateIconInWordDoc()
{
    var wordApp = new Word.Application();
    wordApp.Visible = true;
    wordApp.Documents.Add();
    wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);
}

Mainの最後に次の行を追加します。

// スプレッドシートにリンクされたアイコンを含むWordドキュメントを作成。
CreateIconInWordDoc();

DisplayInExcelの最後に次の行を追加して、ワークシートの内容をクリップボードに追加します。

// スプレッドシート内容をクリップボードにコピー
workSheet.Range["A1:B3"].Copy();

CTRL+F5を押すと、アイコンを含むWordドキュメントが表示されます。アイコンをダブルクリックするとワークシートが前面に表示されます。

まとめ

このガイドでは、C#を用いてMicrosoft Officeアプリケーションとのインタラクションを行う方法を学びました。Excelにデータを表示し、Wordにリンクを作成する手順を説明しました。これらの技術を活用することで、さまざまなビジネスアプリケーションの開発が可能になります。

————-

How to access Office interop objects – C#

Source link

The article published on March 1, 2023, provides a comprehensive walkthrough for using C# to interact with Microsoft Office API objects, specifically targeting Excel and Word applications. It highlights new features in C# that simplify this interaction, including named and optional arguments, a dynamic type, and reference parameter handling in COM methods.

To successfully follow the instructions, users need to have Microsoft Office Excel 2007 and Word 2007 or later versions installed. The article outlines the process of creating a console application in Visual Studio, adding necessary references to the Office Interop assemblies, and writing C# code to accomplish two main tasks:

  1. Creating an Excel Worksheet: It guides users through constructing a list of bank account objects and exporting this data into an Excel worksheet. The code utilizes optional arguments and dynamic types to streamline interactions with COM objects, resulting in a more straightforward coding experience. It also demonstrates how to format the worksheet and automatically adjust column widths.

  2. Creating a Word Document with a Link to Excel: The article goes further to show how to create a Word document that contains an icon linking to the previously created Excel worksheet. It explains the use of named arguments in the PasteSpecial method to simplify method calls.

The article also discusses important considerations regarding the compatibility of VSTO (Visual Studio Tools for Office) with the .NET Framework, stating that while Office Add-ins cannot be created with .NET Core or .NET 5+, VSTO and COM add-ins can still be developed using the .NET Framework. Moreover, it touches on the option to embed type information instead of using primary interop assemblies (PIAs) for easier deployment, version independence, and fewer casting requirements.

In summary, the article serves as a practical guide for developers looking to leverage C# for Office automation tasks, demonstrating key features and providing step-by-step instructions for integrating Excel and Word functionalities.

関連記事

コメント

この記事へのコメントはありません。