次の方法で共有


ドキュメントが開いたときにヘッダーを追加する

次のセクションでは、新規または既存のドキュメントが開いたときにドキュメント ヘッダーを自動的に変更するWord アドインを開発する方法について説明します。 この特定のサンプルはWord用ですが、マニフェストの構成は Excel とPowerPointで同じです。 このスタイルのイベント ベースのアクティブ化パターンの概要については、「イベント を使用してアドインをアクティブ化する」を参照してください。

重要

このサンプルでは、サポートされているバージョンのWordを持つ Microsoft 365 サブスクリプションが必要です。

新しいアドインを作成する

Word アドインのクイック スタートに従って、新しいアドインを作成します。 これにより、イベント ベースのアクティブ化コードを追加できる、動作する Office アドインが提供されます。

注:

このチュートリアルで説明するサンプルの完成したバージョンについては、サンプル GitHub リポジトリの「Word ドキュメントが開いたときにアドインでラベルを自動的に追加する」サンプルを参照してください。

マニフェストを構成する

イベント ベースのアドインを有効にするには、マニフェストの VersionOverridesV1_0 ノードで次の要素を構成する必要があります。

  • Runtimes 要素で、Runtime の新しい Override 要素を作成します。 "javascript" 型をオーバーライドし、トリガーする関数を含む JavaScript ファイルをイベントで参照します。
  • DesktopFormFactor 要素で、イベント ハンドラーを使用して JavaScript ファイルの FunctionFile 要素を追加します。
  • ExtensionPoint 要素で、xsi:typeLaunchEvent に設定します。 これにより、アドインでイベント ベースのアクティブ化機能が有効になります。
  • LaunchEvent 要素で、TypeOnDocumentOpened に設定し、FunctionName属性でイベント ハンドラーの JavaScript 関数名を指定します。

次のマニフェスト コードのサンプルを使用して、プロジェクトを更新します。

  1. コード エディターで、作成したクイック スタート プロジェクトを開きます。

  2. プロジェクトのルートにある manifest.xml ファイルを開きます。

  3. <VersionOverrides> ノード全体 (開いているタグと閉じるタグを含む) を選択し、次の XML に置き換えます。

      <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">
        <Hosts>
          <Host xsi:type="Document">
            <Runtimes>
              <Runtime resid="Taskpane.Url" lifetime="long" />
              <Runtime resid="WebViewRuntime.Url">
                <Override type="javascript" resid="JsRuntimeWord.Url"/>
              </Runtime>
            </Runtimes>
            <DesktopFormFactor>
              <GetStarted>
                <Title resid="GetStarted.Title"/>
                <Description resid="GetStarted.Description"/>
                <LearnMoreUrl resid="GetStarted.LearnMoreUrl"/>
              </GetStarted>
              <FunctionFile resid="Commands.Url"/>
              <ExtensionPoint xsi:type="LaunchEvent">
                <LaunchEvents>
                  <LaunchEvent Type="OnDocumentOpened" FunctionName="changeHeader"></LaunchEvent>
                </LaunchEvents>
                <SourceLocation resid="WebViewRuntime.Url"/>
              </ExtensionPoint>
              <ExtensionPoint xsi:type="PrimaryCommandSurface">
                <OfficeTab id="TabHome">
                  <Group id="CommandsGroup">
                    <Label resid="CommandsGroup.Label"/>
                    <Icon>
                      <bt:Image size="16" resid="Icon.16x16"/>
                      <bt:Image size="32" resid="Icon.32x32"/>
                      <bt:Image size="80" resid="Icon.80x80"/>
                    </Icon>
                    <Control xsi:type="Button" id="TaskpaneButton">
                      <Label resid="TaskpaneButton.Label"/>
                      <Supertip>
                        <Title resid="TaskpaneButton.Label"/>
                        <Description resid="TaskpaneButton.Tooltip"/>
                      </Supertip>
                      <Icon>
                        <bt:Image size="16" resid="Icon.16x16"/>
                        <bt:Image size="32" resid="Icon.32x32"/>
                        <bt:Image size="80" resid="Icon.80x80"/>
                      </Icon>
                      <Action xsi:type="ShowTaskpane">
                        <TaskpaneId>ButtonId1</TaskpaneId>
                        <SourceLocation resid="Taskpane.Url"/>
                      </Action>
                    </Control>
                  </Group>
                </OfficeTab>
              </ExtensionPoint>
            </DesktopFormFactor>
          </Host>
        </Hosts>
        <Resources>
          <bt:Images>
            <bt:Image id="Icon.16x16" DefaultValue="https://localhost:3000/assets/icon-16.png"/>
            <bt:Image id="Icon.32x32" DefaultValue="https://localhost:3000/assets/icon-32.png"/>
            <bt:Image id="Icon.80x80" DefaultValue="https://localhost:3000/assets/icon-80.png"/>
          </bt:Images>
          <bt:Urls>
            <bt:Url id="GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812"/>
            <bt:Url id="Commands.Url" DefaultValue="https://localhost:3000/commands.html"/>
            <bt:Url id="Taskpane.Url" DefaultValue="https://localhost:3000/taskpane.html"/>
            <bt:Url id="WebViewRuntime.Url" DefaultValue="https://localhost:3000/commands.html"/>
            <bt:Url id="JsRuntimeWord.Url" DefaultValue="https://localhost:3000/commands.js"/>
          </bt:Urls>
          <bt:ShortStrings>
            <bt:String id="GetStarted.Title" DefaultValue="Get started with your sample add-in!"/>
            <bt:String id="CommandsGroup.Label" DefaultValue="Event-based add-in activation"/>
            <bt:String id="TaskpaneButton.Label" DefaultValue="My add-in"/>
          </bt:ShortStrings>
          <bt:LongStrings>
            <bt:String id="GetStarted.Description" DefaultValue="Your sample add-in loaded successfully. Go to the HOME tab and click the 'Show Task Pane' button to get started."/>
            <bt:String id="TaskpaneButton.Tooltip" DefaultValue="Click to show the task pane"/>
          </bt:LongStrings>
        </Resources>
      </VersionOverrides>
    
  4. 変更内容を保存します。

イベント ハンドラを実装する

OnDocumentOpened イベントが発生したときにアドインが動作できるようにするには、JavaScript イベント ハンドラーを実装する必要があります。 このセクションでは、 changeHeader 関数を作成します。これにより、新しいドキュメントに "Public" ヘッダーが追加され、コンテンツが既に存在する既存のドキュメントに "機密性の高い" ヘッダーが追加されます。

  1. ./src/commands フォルダーで、 という名前のファイル commands.js開きます。

  2. commands.js の内容全体を次の JavaScript コードに置き換えます。

      /*
      * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
      * See LICENSE in the project root for license information.
      */
      /* global global, Office, self, window */
    
      Office.onReady(() => {
        // If needed, Office.js is ready to be called.
      });
    
      async function changeHeader(event) {
        Word.run(async (context) => {
          const body = context.document.body;
          body.load("text");
          await context.sync();
    
          if (body.text.length === 0) {
          // For new or empty documents, make a "Public" header. 
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            const firstPageHeader = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.firstPage);
            header.clear();
            firstPageHeader.clear();
    
            header.insertParagraph("Public - The data is for the public and shareable externally", "Start");
            firstPageHeader.insertParagraph("Public - The data is for the public and shareable externally", "Start");
            header.font.color = "#07641d";
            firstPageHeader.font.color = "#07641d";
            await context.sync();
          } else {
            // For existing documents, make a "Highly Confidential" header.
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            const firstPageHeader = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.firstPage);
            header.clear();
            firstPageHeader.clear();
            header.insertParagraph("Highly Confidential - The data must be secret or in some way highly critical", "Start");
            firstPageHeader.insertParagraph("Highly Confidential - The data must be secret or in some way highly critical", "Start");
            header.font.color = "#f8334d";
            firstPageHeader.font.color = "#f8334d";
            await context.sync();
          }
        });
    
        // Calling event.completed is required. event.completed lets the platform know that processing has completed.
        event.completed();
      }
    
      async function paragraphChanged() {
        await Word.run(async (context) => {
          const results = context.document.body.search("110");
          results.load("length");
          await context.sync();
          if (results.items.length === 0) {
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            header.clear();
            header.insertParagraph("Public - The data is for the public and shareable externally", "Start");
            const font = header.font;
            font.color = "#07641d";
    
            await context.sync();
          } else {
            const header = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary);
            header.clear();
            header.insertParagraph("Highly Confidential - The data must be secret or in some way highly critical", "Start");
            const font = header.font;
            font.color = "#f8334d";
    
            await context.sync();
          }
        });
      }
    
      async function registerOnParagraphChanged(event) {
        await Word.run(async (context) => {
          let eventContext = context.document.onParagraphChanged.add(paragraphChanged);
          await context.sync();
        });
        // Calling event.completed is required. event.completed lets the platform know that processing has completed.
        event.completed();
      }
    
    
      Office.actions.associate("changeHeader", changeHeader);
      Office.actions.associate("registerOnParagraphChanged", registerOnParagraphChanged);
    
  3. 変更内容を保存します。

アドインをテストして検証する

  1. npm startを実行してプロジェクトをビルドし、Web サーバーを起動します。 開いているWordドキュメントは無視します
  2. 「Office アドインをOffice on the webにサイドロードする」のガイダンスに従って、Web 上のアドイン Wordを手動でサイドロードします。 プロジェクトのルートで manifest.xml を使用します。
  3. web 上のWordで、新しいドキュメントと既存のWord ドキュメントの両方を開いてみます。 ヘッダーは、開いたときに自動的に追加されます。

関連項目