Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
As secções seguintes explicam como desenvolver um suplemento Word que altera automaticamente o cabeçalho do documento quando é aberto um documento novo ou existente. Embora este exemplo específico seja para Word, a configuração do manifesto é a mesma para o Excel e o PowerPoint. Para obter uma descrição geral deste estilo de padrão de ativação baseado em eventos, veja Ativar suplementos com eventos.
Importante
Este exemplo requer que tenha uma subscrição do Microsoft 365 com a versão suportada do Word.
Criar um novo suplemento
Crie um novo suplemento ao seguir o guia de introdução Word suplemento. Isto irá fornecer-lhe um Suplemento do Office funcional ao qual pode adicionar o código de ativação baseado em eventos.
Observação
Para obter uma versão completa do exemplo descrito nestas instruções, veja Adicionar automaticamente etiquetas com um suplemento quando um documento Word abre o exemplo no nosso repositório do GitHub de exemplo.
Configurar o manifesto
Para ativar um suplemento baseado em eventos, tem de configurar os seguintes elementos no VersionOverridesV1_0 nó do manifesto.
- No elemento Runtimes , crie um novo elemento Substituir para Runtime. Substitua o tipo "javascript" e referencie o ficheiro JavaScript que contém a função que pretende acionar com o evento.
- No elemento DesktopFormFactor , adicione um elemento FunctionFile para o ficheiro JavaScript com o processador de eventos.
- No elemento ExtensionPoint , defina como
xsi:typeLaunchEvent. Isto ativa a funcionalidade de ativação baseada em eventos no seu suplemento. - No elemento LaunchEvent , defina como
TypeOnDocumentOpenede especifique o nome da função JavaScript do processador de eventos noFunctionNameatributo .
Utilize o seguinte código de manifesto de exemplo para atualizar o projeto.
No editor de código, abra o projeto de início rápido que criou.
Abra o ficheiro manifest.xml localizado na raiz do projeto.
Selecione todo
<VersionOverrides>o nó (incluindo as etiquetas abertas e fechadas) e substitua-o pelo XML seguinte.<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>Salve suas alterações.
Implementar o manipulador de eventos
Para permitir que o suplemento atue quando o OnDocumentOpened evento ocorre, tem de implementar um processador de eventos JavaScript. Nesta secção, irá criar a changeHeader função, que adiciona um cabeçalho "Público" a novos documentos ou um cabeçalho "Altamente Confidencial" a documentos existentes que já têm conteúdo.
Na pasta ./src/commands , abra o ficheiro com o nome commands.js.
Substitua todo o conteúdo de commands.js pelo seguinte código 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);Salve suas alterações.
Testar e validar o suplemento
- Execute
npm startpara compilar o seu projeto e iniciar o servidor Web. Ignore o Word documento aberto. - Carregue manualmente o suplemento no Word na Web ao seguir a documentação de orientação em Sideload Office Add-ins to Office na Web (Sideload Office Add-ins to Office na Web). Utilize o manifest.xml na raiz do projeto.
- Experimente abrir documentos de Word novos e existentes no Word na Web. Os cabeçalhos devem ser adicionados automaticamente quando abrirem.