打开文档时添加页眉

以下部分将引导你完成如何开发Word加载项,该外接程序在打开新文档或现有文档时自动更改文档标题。 虽然此特定示例适用于Word,但对于 Excel 和 PowerPoint,清单配置是相同的。 有关这种基于事件的激活模式样式的概述,请参阅 使用事件激活加载项

重要

此示例要求具有 Microsoft 365 订阅,其中包含受支持的 Word 版本。

创建新加载项

按照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 web 版 中的指南,手动将加载项旁加载到 web Word。 使用项目根目录中的 manifest.xml
  3. 尝试在 web Word 中打开新的和现有的Word文档。 标头应在打开时自动添加。

另请参阅