Добавление пользовательских функций Excel в существующую надстройку Excel - Javascript Api

У меня есть надстройка excel с пользовательским интерфейсом (с использованием реакции), и я хотел бы добавить к ней некоторые пользовательские функции. Когда я добавляю надстройки по отдельности, обе работают нормально, но когда я пытаюсь объединить их, пользовательские функции не появляются.

Я предполагаю, что моя проблема связана с манифестом, но я не уверен, что это такое: я добавил точку расширения пользовательских функций, добавил бит пользовательских функций в ресурсы Urls и ShortStrings и заменил исходное местоположение html cf на область задач html.

Вот мой манифест:

<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp
          xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
          xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides"
          xsi:type="TaskPaneApp">

  <!-- Begin Basic Settings: Add-in metadata, used for all versions of Office unless override provided. -->

  <!-- IMPORTANT! Id must be unique for your add-in, if you reuse this manifest ensure that you change this id to a new GUID. -->
  <Id>1d9453a6-d50b-4b54-9076-eb0f1d9409c0</Id>

  <!--Version. Updates from the store only get triggered if there is a version change. -->
  <Version>1.0.0.0</Version>
  <ProviderName>[Provider name]</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <!-- The display name of your add-in. Used on the store and various places of the Office UI such as the add-ins dialog. -->
  <DisplayName DefaultValue="Iplicit Excel Add-in" />
  <Description DefaultValue="[Workbook Add-in description]"/>

  <!-- Icon for your add-in. Used on installation screens and the add-ins dialog. -->
  <IconUrl DefaultValue="https://localhost:3000/assets/icon-32.png" />
  <HighResolutionIconUrl DefaultValue="https://localhost:3000/assets/hi-res-icon.png"/>

  <!--If you plan to submit this add-in to the Office Store, uncomment the SupportUrl element below-->
  <!--<SupportUrl DefaultValue="[Insert the URL of a page that provides support information for the app]">-->

  <!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
  <AppDomains>
    <AppDomain>AppDomain1</AppDomain>
    <AppDomain>AppDomain2</AppDomain>
    <AppDomain>AppDomain3</AppDomain>
  </AppDomains>
  <!--End Basic Settings. -->

  <!--Begin TaskPane Mode integration. This section is used if there are no VersionOverrides or if the Office client version does not support add-in commands. -->
  <Hosts>
    <Host Name="Workbook" />
  </Hosts>
  <DefaultSettings>
    <SourceLocation DefaultValue="https://localhost:3000/index.html" />
  </DefaultSettings>
  <!-- End TaskPane Mode integration.  -->

  <Permissions>ReadWriteDocument</Permissions>

  <!-- Begin Add-in Commands Mode integration. -->
  <VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">

    <!-- The Hosts node is required. -->
    <Hosts>
      <!-- Each host can have a different set of commands. -->
      <!-- Excel host is Workbook, Word host is Document, and PowerPoint host is Presentation. -->
      <!-- Make sure the hosts you override match the hosts declared in the top section of the manifest. -->
      <Host xsi:type="Workbook">
        <!-- Form factor. Currently only DesktopFormFactor is supported. -->
        <DesktopFormFactor>
          <!--"This code enables a customizable message to be displayed when the add-in is loaded successfully upon individual install."-->
          <GetStarted>
            <!-- Title of the Getting Started callout. resid points to a ShortString resource -->
            <Title resid="Contoso.GetStarted.Title"/>

            <!-- Description of the Getting Started callout. resid points to a LongString resource -->
            <Description resid="Contoso.GetStarted.Description"/>

            <!-- Point to a url resource which details how the add-in should be used. -->
            <LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/>
          </GetStarted>
          <!-- Function file is a HTML page that includes the JavaScript where functions for ExecuteAction will be called.
            Think of the FunctionFile as the code behind ExecuteFunction. -->
          <FunctionFile resid="Contoso.DesktopFunctionFile.Url" />

          <!-- PrimaryCommandSurface is the main Office Ribbon. -->
          <ExtensionPoint xsi:type="PrimaryCommandSurface">
            <!-- Use OfficeTab to extend an existing Tab. Use CustomTab to create a new tab. -->
            <OfficeTab id="TabHome">
              <!-- Ensure you provide a unique id for the group. Recommendation for any IDs is to namespace using your company name. -->
              <Group id="Contoso.Group1">
                <!-- Label for your group. resid must point to a ShortString resource. -->
                <Label resid="Contoso.Group1Label" />
                <!-- Icons. Required sizes 16,32,80, optional 20, 24, 40, 48, 64. Strongly recommended to provide all sizes for great UX. -->
                <!-- Use PNG icons. All URLs on the resources section must use HTTPS. -->
                <Icon>
                  <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                  <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                  <bt:Image size="80" resid="Contoso.tpicon_80x80" />
                </Icon>

                <!-- Control. It can be of type "Button" or "Menu". -->
                <Control xsi:type="Button" id="Contoso.TaskpaneButton">
                  <Label resid="Contoso.TaskpaneButton.Label" />
                  <Supertip>
                    <!-- ToolTip title. resid must point to a ShortString resource. -->
                    <Title resid="Contoso.TaskpaneButton.Label" />
                    <!-- ToolTip description. resid must point to a LongString resource. -->
                    <Description resid="Contoso.TaskpaneButton.Tooltip" />
                  </Supertip>
                  <Icon>
                    <bt:Image size="16" resid="Contoso.tpicon_16x16" />
                    <bt:Image size="32" resid="Contoso.tpicon_32x32" />
                    <bt:Image size="80" resid="Contoso.tpicon_80x80" />
                  </Icon>

                  <!-- This is what happens when the command is triggered (E.g. click on the Ribbon). Supported actions are ExecuteFunction or ShowTaskpane. -->
                  <Action xsi:type="ShowTaskpane">
                    <TaskpaneId>ButtonId1</TaskpaneId>
                    <!-- Provide a url resource id for the location that will be displayed on the task pane. -->
                    <SourceLocation resid="Contoso.Taskpane.Url" />
                  </Action>
                </Control>
              </Group>
            </OfficeTab>
          </ExtensionPoint>
          <ExtensionPoint xsi:type="CustomFunctions">
            <Script>
              <SourceLocation resid="JS-URL" />
            </Script>
            <Page>
              <SourceLocation resid="Contoso.Taskpane.Url"/>
            </Page>
            <Metadata>
              <SourceLocation resid="JSON-URL" />
            </Metadata>
            <Namespace resid="namespace" />
          </ExtensionPoint>
        </DesktopFormFactor>
      </Host>
    </Hosts>

    <!-- You can use resources across hosts and form factors. -->
    <Resources>
      <bt:Images>
        <bt:Image id="Contoso.tpicon_16x16" DefaultValue="https://localhost:3000/assets/icon-16.png" />
        <bt:Image id="Contoso.tpicon_32x32" DefaultValue="https://localhost:3000/assets/icon-32.png" />
        <bt:Image id="Contoso.tpicon_80x80" DefaultValue="https://localhost:3000/assets/icon-80.png" />
      </bt:Images>
      <bt:Urls>
        <bt:Url id="Contoso.Taskpane.Url" DefaultValue="https://localhost:3000/index.html" />
        <bt:Url id="Contoso.GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812" />
        <bt:Url id="Contoso.DesktopFunctionFile.Url" DefaultValue="https://localhost:3000/function-file/function-file.html" />
        <bt:Url id="JSON-URL" DefaultValue="http://localhost:3000/cf/customfunctions.json"/>
        <bt:Url id="JS-URL" DefaultValue="http://localhost:3000/cf/customfunctions.js"/>
      </bt:Urls>
      <!-- ShortStrings max characters==125. -->
      <bt:ShortStrings>
        <bt:String id="Contoso.TaskpaneButton.Label" DefaultValue="Show Taskpane" />
        <bt:String id="Contoso.Group1Label" DefaultValue="Commands Group" />
        <bt:String id="Contoso.GetStarted.Title" DefaultValue="Get started with your sample add-in!" />
        <bt:String id="namespace" DefaultValue="IPLICIT" />
      </bt:ShortStrings>
      <!-- LongStrings max characters==250. -->
      <bt:LongStrings>
        <bt:String id="Contoso.TaskpaneButton.Tooltip" DefaultValue="Click to Show a Taskpane" />
        <bt:String id="Contoso.GetStarted.Description" DefaultValue="Your sample add-in loaded succesfully. Go to the HOME tab and click the 'Show Taskpane' button to get started." />
      </bt:LongStrings>
    </Resources>
  </VersionOverrides>
  <!-- End Add-in Commands Mode integration. -->

</OfficeApp>   

А это фрагмент html-страницы двух надстроек: https://i.stack.imgur.com/PZqcG.png


person José Salgado    schedule 19.06.2018    source источник
comment
Добро пожаловать в Stack Overflow! Поскольку вы здесь новичок, я рекомендую прочитать несколько советов Как мне задать хороший вопрос?. В вашем вопросе недостаточно подробностей, чтобы помочь сообществу вам помочь. Кроме того, включите код и манифесты непосредственно в свой вопрос. Копать скриншоты крайне больно. :)   -  person Marc LaFleur    schedule 19.06.2018


Ответы (2)


В вашем файле манифеста вам необходимо отделить часть настраиваемой функции от раздела DesktopFormFactor в отдельный раздел AllFormFactors. Так должно получиться

...
   <DesktopFormFactor>
     <ExtensionPoint xsi:type="PrimaryCommandSurface">
...
     </ExtensionPoint>
   </DesktopFormFactor>

   <AllFormFactors>
     <ExtensionPoint xsi:type="CustomFunctions">
...
     </ExtensionPoint>
   </AllFormFactors>
...

Недавно я загрузил образец с настраиваемыми функциями и панелью задач здесь, если это поможет для справки.

person David Chesnut    schedule 19.01.2019

Мой ответ слишком сложен для комментария, поэтому я использую «ответ», а позже исправлю его или удалю по мере необходимости.

Сначала небольшой момент терминологии: если у вас есть один манифест, значит, у вас есть одна надстройка. Ваши ссылки на «две надстройки» сбивают с толку ситуацию. В одной надстройке можно развернуть как область задач, так и набор настраиваемых функций.

Насколько я понимаю, вы смогли успешно развернуть пользовательские функции в надстройке, которая не включает панель задач. Чтобы объединить это с надстройкой области задач, файлы HTML и JavaScript, которые вы использовали для пользовательских функций, должны отличаться от файлов HTML и JavaScript в проекте надстройки области задач. Не следует пытаться использовать один и тот же HTML-файл как страницу в области задач и как загрузчик для пользовательских функций JavaScript.

Я думаю, что вам нужно, по сути, следующее: скопировать файлы html, javascript и json из надстройки пользовательских функций в ту же папку в проекте надстройки панели задач. Затем скопируйте часть точки расширения манифеста надстройки настраиваемой функции и объявленные в ней остатки в соответствующие места в манифесте надстройки области задач.

person Rick Kirkham    schedule 19.06.2018
comment
Не получилось, Рик. Я сделал то, что вы сказали, и все еще не смог развернуть настраиваемые функции с помощью панели задач. В любом случае, спасибо. - person José Salgado; 20.06.2018
comment
Я только что видел это в документации: установите Office (сборка 9325 в Windows или 13.329 на Mac) и присоединитесь к программе предварительной оценки Office. (Обратите внимание, что недостаточно просто получить последнюю сборку; эта функция будет отключена в любой сборке, пока вы не присоединитесь к программе предварительной оценки). Вы в программе? Предложение и ссылка на программу находятся в Шаге 1 этой статьи; docs.microsoft.com/en- us / office / dev / add-ins / excel / - person Rick Kirkham; 20.06.2018
comment
Да, @Rick, я участвую в программе предварительной оценки Office. Я могу загрузить пользовательские функции отдельно. - person José Salgado; 20.06.2018
comment
Вы когда-нибудь получали эту работу? Я пытаюсь добиться того же, т.е. иметь настраиваемые функции и панель задач как часть одной надстройки. - person geochr; 17.07.2018
comment
Нет @geochr, к сожалению, не смог - person José Salgado; 14.01.2019