Export (0) Print
Expand All

How to: Create your first content app for Excel by using "Napa" Office 365 Development Tools

apps for Office

Learn how to create an app for Office by using "Napa" Office 365 Development Tools.

Run button Run this sample now!

Last modified: June 30, 2014

Applies to: Excel 2013 | Excel 2013 RT | Excel 2013 SP1 | Excel Online

   Office.js: v1.0, v1.1

   Apps for Office manifests schema: v1.0, v1.1

Note Note

We can also show you how to build a task pane and content app by using Visual Studio or a text editor. If you’re not sure which tool to use, read the Development basics.

In this article
Prerequisites
Overview
Create a basic app for Office
Add an HTML file to the project
Change the app properties
Get data from a worksheet
Put data into selected cells in a worksheet
Handle an event in a worksheet
Bind to cells in a worksheet
Debug your content app in Windows Internet Explorer
Additional resources

You need the following components to complete this walkthrough:

  • An Office 365 account

  • The "Napa" Office 365 Development Tools app

For more information, see Sign up for an Office 365 Developer Site, set up your tools and environment, and start deploying apps.

By reviewing this walkthrough, you can learn how to create a simple app for Office by using the "Napa" Office 365 Development Tools app. The app that you’ll create gets stock symbols from a worksheet and shows data related to that symbol in the app. This app also shows you how to write data back to the worksheet, handle events and bind to cells in the worksheet.

For more information about "Napa" Office 365 Development Tools, see Create apps for Office and SharePoint by using "Napa" Office 365 Development Tools.

To create a basic app for Office

  1. Choose the Add New Project button.

    Note Note

    The Add New Project button appears only if you have created other projects. If this is your first project, skip to Step 2.

    Figure 1. New project tile

    Add New Project tile
  2. Choose the Content app for Excel tile and name the project MyFirstContentApp. Choose the default Basic app option and then choose the Create button.

    Figure 2. Content app for Excel tile

    Excel app tile

    The code editor opens and shows the default webpage, which already contains some sample code that you can run without doing anything else.

Run the sample app for Office

To run the sample app for Office

  1. On the side of the page, choose the run (Run button) button.

    Excel opens, and the sample app for Office appears so that you can experiment with its features.

  2. When you are ready to move on, close Excel.

You can add HTML pages, JavaScript files, and style sheets to your project just as you would with any other web app.

To add an HTML file to the project

  1. On the side of the page, point to the Pages folder and then choose the New folder button.

    Figure 3. The New folder button.

    The New folder link
  2. Name the folder MyAppPage.

  3. On the side of the page, point to the MyAppPage folder and then choose the Add New Item command on the context menu.

    The New File dialog box appears.

    Figure 5. Add new item button

    Add new item
  4. Choose the HTML Page tile, name the file MyAppPage, and then choose the Create button.

    Figure 6. New File dialog box

    New project dialog box
  5. On the side of the page, point to the MyAppPage folder, choose the arrow, and then choose the add new item button again.

    The New File dialog box appears.

  6. Choose the JavaScript File tile, name the file MyAppPage, and then choose the Create button.

    Next, we will modify the look and feel of the app for Office and point it to the HTML page that you just created.

To change the app properties

  1. On the side of the page, choose the properties (Properties button) button.

    The properties of the app for Office appear.

  2. Set the Name, StartPage, Description, Initial width, and Initial height properties to the values shown in Figure 7.

    Figure 7. Properties dialog box

    Properties page

    The Name and Description properties help users understand the purpose of the app for Office when it appears in a list of available apps for an Office application. The Size property specifies how much space the app for Office requires. The Start Page property points to the page that appears in the app for Office when you start the project.

  3. Choose the Apply button at the bottom of the Properties dialog box, and then choose the Explore button on the left toolbar.

    The property values are saved, and then the Explore pane opens.

    Note Note

    The Properties editor shows the most common settings of an app for Office. It does not show all of the possible settings of an app for Office. If your scenario requires you to modify settings that do not appear in the Properties editor, you can create your app by using Visual Studio or a text editor.

Your app for Office can get the value of a single cell or the values of a collection of cells. You can accomplish this task in the most basic way by getting the value of a single cell that the user chooses in the worksheet. After you complete these steps, you will be able to choose a cell in Excel and then choose a button in the app for Office. The data from the cell that you chose appears in a control in the app for Office.

To get data from a worksheet

  1. On the side of the page, choose MyAppPage.html.

    Figure 8. MyAppPage html file

    MyApp html file

    The MyAppPage webpage appears in the code editor.

  2. Replace all of the code within the <head> tags (including the opening and closing <head> tags with this code.

    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
        <title></title>
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
        
        <link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
        <script src="https://appsforoffice.microsoft.com/lib/1.0/hosted/office.js" type="text/javascript"></script>
        
        <link href="../../Content/App.css " rel="stylesheet" type="text/css" />
        <script src="../../Scripts/App.js" type="text/javascript"></script>
        
        <script src="MyAppPage.js" type="text/javascript"></script>
    </head>
    
    

    This code gives your MyAppPage webpage the same JavaScript libraries and CSS file references as the Default.HTML file. This table briefly describes each file reference.

    File

    Description

    App.css, Office.css

    The default CSS files of the project. You can use these pages to define certain aspects of how the webpage appears.

    MyAppPage.js

    This is the JavaScript file that you created for your page.

    App.js

    Located in the App folder of the project, this is the default JavaScript file of the app. This file contains some example code to get you started.

  3. Replace the opening and closing <body> tags with this code.

    This code adds all of the controls that we will implement over the course of this walkthrough. This code also adds a table that will contain stock data related to symbols that you add to the worksheet.

    <body>
    <div style="padding: 15px; overflow: auto; border: .2em solid #000;">
    
    <table>
    <tr>
    <td>
    
    <button id="get-text" style="width: 100px;">Get symbol</button>
    </td>
    <td>
    <button id="bind-text" style="width: 100px;">Bind to cell</button>
    </td>
    </tr>
    <tr>
    <td>
    <input id="input" style="width: 100px;"/>
    </td>
    <td>
    <button id="add-text" style="width: 100px;">Add symbol</button>
    </td>
    </tr>
    
    </table>
    <h1><div id="stock-name"></div></h1>
    <table border="true">
    <tr>
    <td>
    <table>
    <tr>
    <td>Prev close:</td>
    <td id="prev-close"></td>
    </tr>
    
    <tr>
    <td>Open:</td>
    <td id="open"></td>
    </tr>
    
    <tr>
    <td>Bid:</td>
    <td id="bid"></td>
    </tr>
    <tr>
    <td>Ask:</td>
    <td id="ask"></td>
    </tr>
    <tr>
    <td>1y Target Est::</td>
    <td id="target-est"></td>
    </tr>
    <tr>
    <td>Days range:</td>
    <td id="days-range"></td>
    </tr>
    </table>
    </td>
    <td>
        <table>
    <tr>
    <td>Volume:</td>
    <td id="volume"></td>
    </tr>
    
    <tr>
    <td>Avg daily volume:</td>
    <td id="avg-volume"></td>
    </tr>
    
    <tr>
    <td>Market capitalization:</td>
    <td id="market-cap"></td>
    </tr>
    <tr>
    <td>PE Ratio:</td>
    <td id="pe-ratio"></td>
    </tr>
    <tr>
    <td>Earnings p share:</td>
    <td id="earnings"></td>
    </tr>
    <tr>
    <td>Dividend yield:</td>
    <td id="yield"></td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    </div>
    
    </body>
    
    
    
    
  4. Open the MyAppPage.js file, and then add the following code.

    When you run this code, you’ll add a stock symbol to a cell. This code gets that stock symbol and shows data related to that symbol in a table.

    /// <reference path../../Scripts/App.js" />
    
    (function () {
        "use strict";
        
        // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
    
    
    $('#get-text').click(getTextFromDocument);      
            });
        }
    
    })();
    function getTextFromDocument() {
    
        Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
            { valueFormat: "unformatted", filterType: "all" },
    
            function (asyncResult) {
                showStockData(asyncResult.value);
            });
    
    }
    function showStockData(symbol){
        // Yahoo YQL - http://developer.yahoo.com/yql/ 
    var yql = 'select * from yahoo.finance.quotes where symbol in (\'' + symbol + '\')';
    var queryURL = 'https://query.yahooapis.com/v1/public/yql?q=' + yql + '&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?';
    
    $.getJSON(queryURL, function(results) {
    if(results.query.count > 0)
    {
    var quotes = results.query.results.quote;
    
    $('#stock-name').text(quotes.Name);
    $('#prev-close').text(quotes.PreviousClose);
    $('#open').text(quotes.Open);
    $('#bid').text(quotes.Bid);
    $('#ask').text(quotes.Ask);
    $('#target-est').text(quotes.OneyrTargetPrice);
    $('#days-range').text(quotes.DaysRange);
    $('#volume').text(quotes.Volume);
    $('#avg-volume').text(quotes.AverageDailyVolume);
    $('#market-cap').text(quotes.MarketCapitalization);
    $('#pe-ratio').text(quotes.PERatio);
    $('#earnings').text(quotes.EarningsShare);
    $('#yield').text(quotes.DividendYield);
    
    }
    
    });
    
    }
    
    
    
    
    NoteNote

    Like other methods in the JavaScript API for Office, this method is asynchronous in that it doesn’t prevent the app for Office from performing other operations while this method runs.

    The call to getSelectedDataAsync passes an anonymous function with a parameter, named asyncResult, as the callback argument. When the callback function runs, it uses the asyncResult parameter to access the value property of the AsyncResult object to display the data in the cell that the user chose.

Run it!

To run the code

  1. On the side of the page, choose the run (Run button) button.

    Excel opens, and the app for Office appears.

  2. In Excel, enter MSFT into any cell.

    This abbreviation is the stock-ticker symbol for Microsoft.

  3. In the app for Office, choose the Get symbol button.

    Data related to the ticker symbol MSFT appear in a table.

    Figure 9. Data appearing in a table of the app.

    MSFT appears in the app when you press the button

    This example demonstrates how to get data from a cell. In your app, you might use that technique look up information in a database, get information from another service, or perform a calculation. You could add code to perform those sorts of operations to the anonymous function that you pass as a parameter to the getSelectedDataAsync method.

  4. Close Excel.

    In the next example, you'll take data that the user enters into a control on the app, and you'll put that data into a cell in the worksheet.

Your app for Office can put data into any cell or collection of cells. You can accomplish this task in the most basic way by putting data into a cell that the user chooses in the worksheet. After you complete these steps, a user will be able to add text to a cell in the worksheet by choosing a button in the app.

  1. In the code editor, open the MyAppPage.js file, and then add the following code.

    function addTextToDocument() {
    
        var e = document.getElementById("input");
        var text = e.value;
    
        Office.context.document.setSelectedDataAsync(text,
            function (asyncResult) {});
    }
    
    

    This code gets the text from the text box and places that text into a cell that the user chooses in the worksheet.

  2. Update the $(document).ready function as shown in the following example.

    Office.initialize = function (reason) {
            $(document).ready(function () {
    $('#get-text').click(getTextFromDocument);
    $('#add-text').click(addTextToDocument);
                
            });
        }
    
    

Run it!

To run the code

  1. On the side of the page, choose the run (Run button) button.

    Excel opens, and the app for Office appears.

  2. In Excel, choose any cell.

  3. In the app, enter YHOO in the text box next to the Add Symbol button, and then choose the Add symbol button.

    The text YHOO appears in the cell that you chose.

    Figure 10. The text MSFT appearing in the selected cell

    MSFT appears in a cell when you press the button

    This example is simple, but it shows how to put data into a cell. Your app for Office might use a stock service to obtain the closing price of a stock and then add that price to a cell, which might perform other calculations.

  4. Close Excel.

So far, your app for Office requires the user to choose a button to get and set data. By performing the following two steps, you can also get and set data automatically when a user chooses a cell.

To handle an event in a worksheet

  1. In the code editor, open the MyAppPage.js file, and then add the following code to the jQuery .ready() function: $(document).ready().

    
            Office.context.document.addHandlerAsync
            (Office.EventType.DocumentSelectionChanged, updateApp);
    
    
    

    This code declares a method called when the user chooses a cell.

    After you’ve added the code, the Office.initialize function appears as follows.

    Office.initialize = function (reason) {
            $(document).ready(function () {
    $('#get-text').click(getTextFromDocument);
    $('#add-text').click(addTextToDocument);
            Office.context.document.addHandlerAsync
            (Office.EventType.DocumentSelectionChanged, updateApp);
                
            });
        }
    
    
  2. Add the following code to the MyAppPage.js file.

    function updateApp()
    {
            getTextFromDocument();
    }
    
    

    This method is called when a user chooses a cell. This code calls the method that you defined earlier in this walkthrough. That method gets the value of the chosen cell (stock symbol) and shows data related to that symbol in a table.

Run it!

To run the code

  1. On the side of the page, choose the run (Run button) button.

    Excel opens, and the app for Office appears.

  2. In the app, enter MSFT in the text box next to the Add symbol button, and then choose the Add symbol button.

  3. Choose another cell, and then choose the cell that contains MSFT.

    ticker data for the symbol MSFT appears in the table.

  4. Close Excel.

The most advanced way to get and set data is to establish a binding with a cell or a collection of cells in a worksheet. You can prompt users to choose the cells that they want the app for Office to use. Then, you can get data from those cells or put data into those cells at any time. You can enable that scenario by performing these steps.

To bind to cells in a worksheet

  1. In the code editor, open the MyAppPage.js file, and then add this code. This code establishes a binding to a cell that the user chooses. This code also defines a method called when the data in the bound cell changes.

    function addBindingFromSelection() {
        Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text, { id: 'MyBinding' },
            function (asyncResult) {
                Office.select("bindings#MyBinding").addHandlerAsync
                   (Office.EventType.BindingDataChanged, onBindingSelectionChanged);
            }
        );
    }
    
    
    function onBindingSelectionChanged(eventArgs) {
    
        Office.select("bindings#MyBinding").getDataAsync
            (function (asyncResult) {
    
                if (asyncResult.value !== "") {
                    showStockData(asyncResult.value);
    
    
    
                }
    
             });
    }
    
    
  2. Update the $(document).ready function as shown in the following example.

    Office.initialize = function (reason) {
            $(document).ready(function () {
    $('#get-text').click(getTextFromDocument);
    $('#add-text').click(addTextToDocument);
    $('#bind-text').click(addBindingFromSelection);
    
            Office.context.document.addHandlerAsync
            (Office.EventType.DocumentSelectionChanged, updateApp);
    
            });
        }
    
    

Run It!

To run the code

  1. On the side of the page, choose the run (Run button) button.

    Excel opens, and the app for Office appears.

  2. In Excel, select any cell. Then, in the app for Office, choose the Bind to cell button.

  3. In the app, enter MSFT in the text box next to the Add Symbol button, and then choose the Add symbol button.

    The text MSFT appears in the cell that you chose. Because the value of the cell changed, data related to that cell appears in the table.

    Figure 11. table shows data for the ticker symbol MSFT.

    Shows binding to a cell
  4. Close Excel.

If you start your app in Excel Online, and you use Windows Internet Explorer (IE) 9 and up, you can use F12 developer tools to debug the JavaScript, HTML, and Cascading Style Sheets (CSS) of your content app.

The following procedure shows you how to open F12 tools, start the debugger, and cause execution to stop on a line of code in your MyAppPage.js file.

To get started debugging your content app in Windows Internet Explorer

  1. On the side of the page, choose the run (Run button) button.

    Excel opens, and the app for Office appears.

  2. In Excel, select the content app so that the app is in focus when you start the debugging tools.

  3. Press the F12 key on your keyboard.

    The F12 tools open in a separate window.

  4. In the F12 tools window, choose the Script tab, and then choose the Start debugging button.

  5. From the View Sources drop-down list under the Stop debugging button, select MyAppPage.js.

    The contents of the MyAppPage.js file appears in the left pane of the window.

  6. Set a breakpoint next to the addTextToDocument method.

    For more information about how to set a breakpoint in the F12 tool window, see Breaking Code Execution.

  7. In the app, enter MSFT in the text box above the Add Symbol button, and then choose the Add symbol button.

    In the F12 tools window, execution stops on the addTextToDocument method.

    For more information, see any of the following topics.

    If you use a browser other than Windows Internet Explorer, consult your browser documentation.

Now that you’ve created a basic content app for Excel, consider exploring the following paths:

  • Share your project with someone by choosing the Share Project (The Share Project button). "Napa" Office 365 Development Tools creates a copy of your project and provides you with a public link that you can give to anyone.

  • Publish your app by choosing the Publish button (Publish button).

    For more information, see How to: Publish an app for Office.

  • Open your project in Visual Studio by choosing the Open in Visual Studio (Open in Visual Studio button) button. "Napa" Office 365 Development Tools automatically installs the necessary tools and opens your project in Visual Studio.

    You can also download and install these tools directly by visiting the Downloads page of the Apps for Office and SharePoint Dev Center. For more information, see Downloads.

  • Create a task pane app for Excel by using Visual Studio. For more information, see How to: Create your first task pane or content app by using Visual Studio.

Show:
© 2014 Microsoft