Search code examples
angulartypescriptoffice-jsoffice-addinsoffice-js-helpers

How to define Excel using microsoft office-js in Angular 6


I am following this site to integrate office js

On declaring like this:

import * as Excel from '@microsoft/office-js/excel' It's showing compile time error:

Cannot find module '@microsoft/office-js/excel'

On declaring like this:

declare var Excel: any

It's showing run time error:

ERROR ReferenceError: Excel is not defined

Please suggest how to declare it. I need to use it like this:

Excel.run(session, (context){
   ...
});

Solution

  • Install office type definition:

    npm install --save @types/office-js
    

    In tsconfig.app.json you add:

    "types": [
        "office-js"
    ]
    

    In main.ts you bootstrap app as:

        Office.initialize = function () {
        platformBrowserDynamic().bootstrapModule(AppModule);
    };
    

    In index.html you add:

    <script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
    

    After that you should be able to write something like this in your angular service:

      getExtension(): string {
        if (Office.context.host === Office.HostType.Word) {
          return '.docx';
        } else if  (Office.context.host === Office.HostType.Excel) {
          return '.xlsx';
        } else if (Office.context.host === Office.HostType.PowerPoint) {
          return '.pptx';
        } else {
          return null;
        }
      }
    

    Here you can find a sample of angular office-js project:

    Angular office-js sample project

    It is Angular 6 build with Angular CLI version 6.0.8