Error: The reference to Excel is not recognized

I am looking to develop an Office add-in using angularjs and angularjs-ui-router:

<bt:Urls>
    <bt:Url id="Contoso.Taskpane3.Url" DefaultValue="https://localhost:3000/addin/test" />            
</bt:Urls>

The module name is app, and the router configuration is as follows:

.state('addinTest', {
    url: '/addin/test',
    tempalte: 'abc',
    controller: 'TestCtrl',
    resolve: {
        loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
            return $ocLazyLoad.load('https://appsforoffice.microsoft.com/lib/1/hosted/office.js');
        }],
        initOffice: ['loadMyCtrl', function (loadMyCtrl) {
            Office.initialize = function (reason) {
                $(document).ready(function () {
                    angular.element(document).ready(function () {
                        angular.bootstrap(document, ['app'])
                    })
                });
            }
            return Promise.resolve(null)
        }]
    }
})

Here is the controller code:

app.controller('TestCtrl', [function () {
    function loadDataAndCreateChart() {
        Excel.run(function (ctx) {
            var sheet = ctx.workbook.worksheets.getActiveWorksheet();
            sheet.getRange("A1").values = "Quarterly Sales Report";
            return ctx.sync()
        })
    }
    loadDataAndCreateChart()
}])

When loading the add-in, the expected behavior is to write Quarterly Sales Report to cell A1. However, an error was encountered:

ReferenceError: Excel is not defined at loadDataAndCreateChart

Is there a solution to this issue? Also, is it acceptable to initialize Office in this manner and use angular.bootstrap like shown above?

Answer №1

Ensure that calls similar to the following are carried out only after Office initialization:

Excel.run(function (ctx) {
        var sheet = ctx.workbook.worksheets.getActiveWorksheet();
        sheet.getRange("A1").values = "Quarterly Sales Report";
        return ctx.sync()
    });

I have developed a simple application that runs the provided code using just three files.

  1. manifest.xml
  2. index.html
  3. app.js

Remember to replace instances of PathToYourLocalFile with your actual local path in the following files.

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<OfficeApp xsi:type="TaskPaneApp" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/office/appforoffice/1.0">
     <Id>6ed5a5d8-57e4-4739-9a38-cff59f23e266</Id>
     <Version>1.0.0.0</Version>
     <ProviderName>Test Provider</ProviderName>
     <DefaultLocale>en-US</DefaultLocale>
     <DisplayName DefaultValue="Test" />
     <Description DefaultValue="Angular Test" />
     <Capabilities>
        <Capability Name="Workbook" />
     </Capabilities>
     <DefaultSettings>
         <SourceLocation DefaultValue="PathToYourLocalFile/index.html" />
     </DefaultSettings>
     <Permissions>ReadWriteDocument</Permissions>
</OfficeApp>

index.html

You can observe from the app.js file that the loadDataAndCreateChart method is executed post the completion of Office initialization.

To learn how to add the manifest to Excel, refer to the documentation on the Office Dev Center.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve the date value of Focus+Context by using the Brushing Chart

Currently, I am engaged in analyzing the sentiment of tweets on Twitter. The analysis will produce an overall area graph that allows me to choose a specific date range and extract all or some of the tweets falling within that range. In order to create a t ...

What is the best method for extracting the innerHTML value of html tags using a css selector or xpath?

I am currently struggling with retrieving the HTML inner text value using CSS selector or XPath. While I can achieve this using document.getElementById, I am unable to do so using selectors. I can only print the tag element but not the text from it. For e ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

Angular material table cell coloring

Here is my current setup: I have an array of objects like this: users : User []; average = 5; compareValue (value){ ...} And I am displaying a table as shown below: <table mat-table [dataSource]="users"> <ng-container matColumnDef= ...

Do the "Save to Drive" buttons require manual cleaning?

Utilizing the Google Drive API for JavaScript within a VueJS application can be done as follows: In your index.html <script type="text/javascript"> window.___gcfg = { parsetags: 'explicit', lang: 'en-US' }; </scri ...

Tips on obtaining the data count from using the $.get method

Here is the code I'm currently working with: $.get('getstatsAccepted' + tickerid, {tickerid: tickerid}, function(data) { alert(data.length); }, 'json'); I am interested in obtaining the numbe ...

Waiting for templates to load before firing an event in AngularJS

My issue arises from firing an event during the run phase. When multiple directives listen for this event and execute code, some directives on my development machine miss the event because they acquire the template through the templateUrl property before c ...

Guide to creating seamless integration between AngularJS routing and ExpressJS routing when using html5mode

Yesterday, I posted a question on stackoverflow about my webpage's CSS and JavaScript not including after a refresh. I discovered that it was caused by html5mode, but I have been searching for a solution since then with no luck getting an answer. My ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Tips for placing a div within a curved div?

I've got a nested div situation, <div style="background-color: red; height: 100px; width: 100px; border-radius: 10px;" id="div1"> <div style="background-color: orange;" id="div2"> testing </div> </div ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Learn how to send JSON data to REST services from a webpage using the POST method, similar to how it is done in the advanced REST client

Is there a way to call restful services from a webpage and pass JSON data for the POST method, similar to what we can do in an advanced REST client? ...

What is the best way to add an array of JSON objects to another array of JSON objects?

The current JSON array obtained from the response is as follows: comments:[{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…},…] 0:{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…} createdBy:{id: "cf2 ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

When I log out and hit the back button, the PHP page continues to display without any changes

After logging out of my PHP session and being redirected to the login page, I am facing an issue where pressing the back button shows me the previous page without requiring a login. How can I fix this problem? Thank you in advance. index.php <form sty ...

How to Retrieve iFrame URL Using JQuery / Javascript

My webpage contains the following elements... <div> <iframe id="mainContent"> <iframe id="littleBox"> </div> and I am looking to achieve the following functionality... $(".someButton").live('click', function() { ...

Loading Data Using AJAX with JSON on Button Press - Dealing with Array Problems

I am trying to understand how to specifically select JSON objects when a line item meets certain variable criteria that is passed when a button is clicked. Currently, I have it working but the output displays as [object],[object]. I suspect this is happeni ...

Pros and Cons of Using HTML5 Mode versus Hash Mode in AngularJS

When using AngularJS 1.3, it is necessary to include the <base> tag in HTML5 mode. This led me to consider the pros and cons of HTML5 mode versus Hash mode. In Hash mode, the major drawback is that URLs can appear unattractive and may not be easy fo ...

What is the best way to fill out a secondary drop

Is it possible to dynamically populate a secondary selection based on the User's choice in the first selection? For example, if the user selects "Silver," how can I automatically remove "Silver" from the second selection options? var b = { img: ...

Exclude a select few rows in MatSort, rather than excluding entire columns

When the user clicks on the Date column for sorting, it is required to exclude empty rows from the sorting. Empty rows are present due to the application of ngIf on those particular rows. The requirement states that rows with empty column values should eit ...