Export (0) Print
Expand All

How to: Create your first task pane or content app with Visual Studio

apps for Office

This topic shows you how to use Visual Studio to create a Hello World app for Office and then extend it to read, write, and bind to the document.

Last modified: September 24, 2014

Applies to: Excel 2013 | Excel 2013 RT | Excel 2013 SP1 | Excel Online | PowerPoint 2013 | PowerPoint 2013 RT | PowerPoint 2013 SP1 | PowerPoint Online | Project 2013 | Project 2013 SP1 | Word 2013 | Word 2013 RT | Word 2013 SP1

   Office.js: v1.0, v1.1

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

In this article
Prerequisites
Overview
Create a project for the app
Develop the app
Modify the app to run in Word
Modify the app to run as a content app
Next steps
Additional resources

Install the following components before you get started:

  • Microsoft Visual Studio 2013 and the Microsoft Office Developer Tools for Visual Studio 2013 (March 2014 Update)
    -or-
    Microsoft Visual Studio 2012 and the Microsoft Office Developer Tools for Visual Studio 2012.

    You can download the Office Developer Tools for Visual Studio 2012 from the Office Dev Center.

    To download Visual Studio 2013, see the Visual Studio Downloads page.

  • Excel 2013

  • Word 2013

We'll start by creating and running a simple Hello World task pane app in Excel. Then we'll extend the app to perform the following tasks:

  • Write data to the current selection in the worksheet.

  • Read data from the current selection in the worksheet and display it in the app UI.

  • Create a binding to the current selection in the worksheet.

  • Read the data in the binding and display it in the app UI.

  • Add an event handler to read and display data whenever data in the binding is changed.

Finally, we'll make changes to some project settings and the manifest to do the following:

  • Run the task pane app in Word.

  • Run the app as a content app in Excel.

To get started, create an Apps for Office project in Visual Studio.

To create a project in Visual Studio

  1. On the Visual Studio menu bar, choose File, New, Project.

    The New Project dialog box opens.

  2. In the list of project types under Visual C# or Visual Basic, expand Office/SharePoint, choose Apps, and then choose App for Office.

  3. Name the project HelloWorld, and then choose OK.

    The Create App for Office dialog box opens. In Visual Studio 2013, the option Task pane app is selected. Choose the Next button, leave the check boxes for Excel, Word, PowerPoint, and Project selected, and then choose Finish.

    In Visual Studio 2012, the option Task pane app in is selected along with the check boxes for Excel, Word, PowerPoint, and Project. That's what we want, so leave those options selected, and then choose Finish.

    Visual Studio creates the project, and its files appear in Solution Explorer. The default Home.html page opens in Visual Studio.

To design the appearance of the app, you add HTML to the default page of the project. To design the functionality and programming logic for your app, you can add JavaScript code directly in the HTML page, but in this example, you'll add the code to the default JavaScript file (Home.js).

To create a Hello World app

  1. In the Home.html file, delete all of the tags between the opening and closing <body> tags, and then type <div>Hello World!</div> inside the opening and closing body tags. The finished HTML should look like the following.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
        <title></title>
        <script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    
        <link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
        <!-- <script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js" type="text/javascript"></script> -->
    
        <!-- To enable offline debugging using a local reference to Office.js, use:                        -->
        <script src="../../Scripts/Office/MicrosoftAjax.js" type="text/javascript"></script>
        <script src="../../Scripts/Office/1.1/office.js" type="text/javascript"></script>
    
        <link href="../App.css" rel="stylesheet" type="text/css" />
        <script src="../App.js" type="text/javascript"></script>
    
        <link href="Home.css" rel="stylesheet" type="text/css" />
        <script src="Home.js" type="text/javascript"></script>
    </head>  
      <body>
        <div>Hello World!</div>
      </body>
    </html>
    
  2. If you're using Visual Studio 2013, do the following steps.

    1. In Solution Explorer, choose the HelloWorld app.

    2. In the Properties window, verify that the Start Action property is set to Office Desktop Client.

    3. Verify that the Start Document property is set to [New Excel Workbook].

      If you were to choose Internet Explorer as the Start Action property and [New Excel Workbook] as the Start Document property, then the Excel Web App would start when you run the app. When you choose Office Desktop Client as the Start Action property, then Excel in a local installation of Office starts. For this example, you'll be using a local installation of Excel.

  3. For all versions of Visual Studio, on the Debug menu, choose Start Debugging or press the F5 key.

    Excel opens a blank workbook and app appears in the task pane.

    Figure 1. Hello World task pane app

    Hello World task pane app
  4. Close the workbook file.

    Debugging stops and focus returns to Visual Studio.

In the following procedures, we'll extend your Hello World app to access data in the worksheet.

To write data to the worksheet

  1. Replace <div>Hello World!</div> inside the opening and closing <body> tags of the HelloWorld.html page with the following HTML.

    <button id="writeDataBtn"> Write Data </button><br />
    <button id="readDataBtn"> Read Selected Data </button><br />
    <button id="bindDataBtn"> Bind Selected Data </button><br />
    <button id="readBoundDataBtn"> Read Bound Data </button><br />
    <button id="addEventBtn"> Add Event </button><br />
    <span>Results: </span><div id="results"></div>
    

    This adds some buttons to perform data access actions and a div to display results in the HTML page of the app. Next, we'll call the writeData() function to write sample text to the current selection.

  2. Open the Home.js file (HelloWorld.js in Visual Studio 2012) to display the default JavaScript file for the app. If it's not already open, you can find it in Visual Studio 2013 Solution Explorer under App, Home. In Visual Studio 2012, the file is located under Scripts, Office.

  3. Add an event handler $("#writeDataBtn").click to the $(document).ready code to respond when a user clicks the Write Data button. The code should like the following.

    // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
                app.initialize();
                $('#get-data-from-selection').click(getDataFromSelection);
                $("#writeDataBtn").click(function (event) {
                    writeData();
                });
            });
        };
    
  4. Add the following functions to the Home.js file.

    function writeData() {
        Office.context.document.setSelectedDataAsync("Hello World!", function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            }
        });
    } 
    function writeToPage(text) {
        document.getElementById('results').innerText = text;
    }
    
    NoteNote

    Do not to delete or overwrite the Office.initialize event handler function (although you can replace the code within it). The Office.initialize event handler must be in place for your app to initialize correctly at runtime.

    The code in the writeData() function calls the Document.setSelectedDataAsync method to write "Hello World!" to the current cell when you choose the Write Data button. Most of the methods used in this walkthrough are asynchronous, which is why their names end with "Async", and callback functions like the anonymous function passed as the argument following "Hello World!" are used. For more information about using "Async" methods, see Asynchronous programming in apps for Office.

    The writeToPage(text) function is a helper function for writing text back to the results div on the app HTML page. The writeToPage(text) function is also used to display data and messages in the code examples in the following procedures.

  5. On the Debug menu, choose Start Debugging or press the F5 key.

  6. Choose the Write Data button to write "Hello World!" to the current cell, but don't close the workbook or stop debugging yet.

    Figure 2. Write text

    Write text
  7. Switch back to the code editor, and replace "Hello World!" in the call to the setSelectedDataAsync method with [["red"],["green"],["blue"]] like this.

    function writeData() {
        Office.context.document.setSelectedDataAsync([["red"],["green"],["blue"]], function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            }
        });
    }
    

    Writing an array of arrays like [["red"],["green"],["blue"]] creates what's called a matrix data structure, which in this case creates a single column of three cells (rows). You can create a matrix of two columns of three rows like this:

    [["red", "rojo"],["green", "verde"],["blue", "azul"]]

    You can create a single row of three cells like this:

    [["red","green","blue"]]

  8. Choose Ctrl+S to save this change to the code.

  9. Now switch back to the workbook, open the shortcut menu for the app task pane, and then choose Reload.

    This reloads the HTML page with the updated JavaScript code.

  10. Move the selection to a new cell, and then choose the Write Data button.

    This writes the array containing red, green, and blue to a single column of three cells.

    Figure 3. Write matrix

    Write matrix
  11. Close the workbook to stop debugging.

To read data from the worksheet

  1. In Solution Explorer, open the Home.js file.

  2. Add an event handler $("#readDataBtn").click to the $(document).ready code to respond when a user clicks the Read Selected Data button. The code should like the following.

    // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
                app.initialize();
                $('#get-data-from-selection').click(getDataFromSelection);
                $("#writeDataBtn").click(function (event) {
                    writeData();
                });
                $("#readDataBtn").click(function (event) {
                    readData();
                });
            });
        };
    
  3. Add the following code to the Home.js file below the functions you added in the previous procedure.

    function readData() {
        Office.context.document.getSelectedDataAsync("matrix", function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            } 
            else{
                writeToPage('Selected data: ' + asyncResult.value);
            }
        });
    }
    

    The readData() function calls the Document.getSelectedDataAsync method to read the data that's currently selected by the user as a "matrix" coercionType, which is a 2-D array. For Excel, this will read a contiguous range of one or more cells.

  4. On the Debug menu, choose Start Debugging or press the F5 key.

  5. Choose the Write Data button, leave the three cells that have red, green, and blue in them selected, and then choose the Read Selected Data button.

    This reads the data from the three cells as a matrix data structure, and then writes those values to the app page.

    Figure 4. Read matrix

    Read matrix
  6. Close the workbook to stop debugging.

To create a binding for selected data and read the bound data

  1. In Solution Explorer, open the Home.js file.

  2. Add event handlers $("#bindDataBtn").click and $("#readBoundDataBtn").click to the $(document).ready code to respond when a user clicks the Bind Selected Data and Read Bound Data buttons. The code should like the following.

    // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
                app.initialize();
                $('#get-data-from-selection').click(getDataFromSelection);
                $("#writeDataBtn").click(function (event) {
                    writeData();
                });
                $("#readDataBtn").click(function (event) {
                    readData();
                });
                $("#bindDataBtn").click(function (event) {
                    bindData();
                });
                $("#readBoundDataBtn").click(function (event) {
                    readBoundData();
                });
            });
        };
    
  3. Add the following code to the Home.js file below the function you added in the previous procedure.

    function bindData() {
        Office.context.document.bindings.addFromSelectionAsync("matrix", { id: 'myBinding' }, 
            function (asyncResult) {
                if (asyncResult.status === "failed") {
                    writeToPage('Error: ' + asyncResult.error.message);
                } else {
                    writeToPage('Added binding with type: ' + asyncResult.value.type + ' and id: ' +
                        asyncResult.value.id);
                }
            });
    }
    

    The bindData() function calls the Bindings.addFromSelectionAsync method to create a matrix binding with an idof myBinding that is associated with the cells that the user selected. You can specify the bindingType as "text" to create a binding to a single cell in Excel, or to run of characters (a string) in a Word document. For more information about bindings, see Binding to regions in a document or spreadsheet.

  4. Add the following code to the HelloWorld.js file below the bindData () function.

    function readBoundData() {
        Office.select("bindings#myBinding").getDataAsync({ coercionType: "matrix" }, 
            function (asyncResult) {
                if (asyncResult.status === "failed") {
                    writeToPage('Error: ' + asyncResult.error.message);
                } else {
                    writeToPage('Selected data: ' + asyncResult.value);
                }
            });
    }
    

    The readBoundData() function calls the Office.select method to get the binding created by the bindData() function, which has an id of myBinding. (Alternatively, you can use the Bindings.getByIdAsync method to access a binding by its id.) The function then calls the Binding.getDataAsync method to read the data from the binding. Because the binding is a matrix binding, you must specify the coersionType as "matrix" for the call to succeed.

  5. On the Debug menu, choose Start Debugging or press the F5 key.

  6. Choose the Write Data button, leave three cells that have red, green, and blue in them selected, and then choose the Bind Selected Data button.

    This creates a matrix binding that is associated with the three selected cells that have the id myBinding.

    Figure 5. Create a binding

    Create a binding
  7. Move the selection off of the three cells, and then choose the Read Bound Data button.

    This will read the data from the binding created in the previous procedure, and then write those values to the app page. If you didn't change the values, red, green, and blue will be displayed in the app.

  8. Change one or more values in the three cells, press the Enter key after each change, and then choose Read Bound Data again.

    This will read the changed data and display it in the app.

    Figure 6. Read from binding

    Read from binding
  9. Close the workbook to stop debugging.

Now let's add an event handler that will read and display the data in the binding whenever it is changed.

To add an event handler

  1. Add an event handler $("#addEventBtn").click to the $(document).ready code to respond when a user clicks the Add Event button. The code should like the following.

    // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
                app.initialize();
                $('#get-data-from-selection').click(getDataFromSelection);
                $("#writeDataBtn").click(function (event) {
                    writeData();
                });
                $("#readDataBtn").click(function (event) {
                    readData();
                });
                $("#bindDataBtn").click(function (event) {
                    bindData();
                });
                $("#readBoundDataBtn").click(function (event) {
                    readBoundData();
                });
                $("#addEventBtn").click(function (event) {
                    addEvent();
                });
            });
        };
    
  2. Add the following code to the Home.js file below the functions you added in the previous procedure.

    function addEvent() {
        Office.select("bindings#myBinding").addHandlerAsync("bindingDataChanged", myHandler, function (asyncResult) {
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            } else {
                writeToPage('Added event handler');
            }
        });
    }
    function myHandler(eventArgs) {
        eventArgs.binding.getDataAsync({ coerciontype: "matrix" }, function (asyncResult) {
    
            if (asyncResult.status === "failed") {
                writeToPage('Error: ' + asyncResult.error.message);
            } else {
                writeToPage('Bound data: ' + asyncResult.value);
            }
        });
    }
    

    The addEvent() function calls the Office.select method to get the myBinding binding object, and then calls the Binding.addHandlerAsync method to add an event handler for the Binding.bindingDataChanged event. The myHandler function uses the binding property of the BindingDataChangedEventArgs object to access the binding that raised the event, and then calls the Binding.getDataAsync method to read and display the data when the event occurs.

  3. On the Debug menu, choose Start Debugging or press the F5 key.

  4. Choose the Write Data button, leave three cells that have red, green, and blue in them selected, and then choose the Bind Selected Data button.

  5. Choose the Add Event button.

    This retrieves the binding with id of myBinding, and then adds the myHandler function as the handler for the DataChanged event.

    Figure 7. Handling the DataChanged event

    Handling the DataChanged event
  6. Change one or more values in the three bound cells, and press the Enter key after each change.

    This will read the changed data and display it in the app task pane.

  7. Close Excel to stop debugging.

In the next section we'll modify the app project so that you can run and test it in Word.

You can perform the following steps to modify this app project so that it will run and debug in Word 2013:

  • Change the Start Document property of the project to start Word when debugging.

  • Run and debug in Word.

To change the Start Document property in the Debugging property page of the project

  1. In Solution Explorer, choose the project name (HelloWorld).

    The Project Properties property page for the project appears in the pane below Solution Explorer.

  2. Under App, in the Start Document list, choose [New Word Document].

    The Start Action property is already set to Office Desktop Client, so all that's needed is to change the target document.

    Figure 8. Setting the Start Document

    Setting the Start Action

To debug the app in Word

  1. On the menu bar, choose Debug, Start Debugging.

    Word 2013 opens with the HelloWorld app in the task pane.

  2. Choose the Write Data, Read Selected Data, Bind Selected Data, Read Bound Data, and Add Event buttons to perform the same actions as when working in Excel.

    Note Note

    In Word, the event handler won't run to display the bound data until you move the cursor outside of the table inserted by the Write Data button.

    Figure 9. Debugging in Word

    Debugging in Word

You can perform the following steps to modify this app project so that it will run as a content app in Excel:

  • Modify the manifest file to set the xsi:type attribute to "ContentApp" in the OfficeApp element.

  • Modify the manifest file to set values for the RequestedWidth and RequestedHeight elements.

  • Modify the manifest file to remove the "Presentation", "Project", and "Document"Capability elements from the Capabilities element.

  • Change the Start Document property of the project to start in Excel.

To modify the manifest file

  1. In Solution Explorer, open the HelloWorld.xml file.

  2. In the opening OfficeApp tag, change the value of the xsi:type attribute to "ContentApp".

    <OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ContentApp">
    

    The xsi:type attribute specifies the type of app for Office, which determines how the app runs when the user inserts it into a document or workbook. The previous value, "TaskPaneApp", specifies that the app runs in a task pane. Changing xsi:type to "ContentApp" specifies that the app runs in line with the workbook content as a content app.

    NoteNote

    In this release of Office, content apps can run only in the client applications that support content apps. After you change xsi:type to "ContentApp" in the manifest, this app will run only in Excel 2013 or Excel Online.

  3. Add the following RequestedWidth and RequestedHeight elements in the manifest within the <DefaultSettings> tags.

    <DefaultSettings>
      <SourceLocation DefaultValue="~remoteAppUrl/App/Home/Home.html" />
      <RequestedWidth>200</RequestedWidth>
      <RequestedHeight>200</RequestedHeight>
    </DefaultSettings>
    
  4. Remove the "Presentation", "Project", and "Document"Capability elements from the Capabilities element, so that only the "Workbook"Capability element remains.

    <Capabilities>
      <Capability Name="Workbook" />
    </Capabilities>
    
  5. Save these changes to the HelloWorld.xml file.

To change the Start Document property in the Debugging property page of the project

  1. In Solution Explorer, choose the project name (HelloWorld).

    The Project Properties property page for the project appears in the pane below the Solution Explorer.

  2. Under App, in the Start Document list, choose Microsoft Excel.

To debug the app in Excel

  1. On the menu bar, choose Debug, Start Debugging.

    Excel 2013 opens with the HelloWorld app running as a content app in the worksheet.

  2. Choose the Write Data, Read Selected Data, Bind Selected Data, Read Bound Data, and Add Event buttons to perform the same actions as before.

    Figure 10. Debugging as a content app

    Debugging as a content app

This topic showed you how to create a Hello World task pane app for Excel, and then add some UI and JavaScript to read, write, and bind to data in the worksheet. We also added a simple event handler to the binding to re-read its data whenever it is changed. We then changed the Start Action to run the same code as a task pane app in Word. Finally, we modified the manifest to run the app as a content app in an Excel worksheet.

To learn more about developing apps for Office, see the following sections of the documentation:

Section

Description

Design apps for Office

Get information about design guidelines.

Develop apps for Office

Learn about tools and development concepts.

Publish apps for Office

Learn about deploying and publishing.

How to: Publish an app for Office

Learn how to deploy and publish an app from Visual Studio.

Tip Tip

To deploy and publish an app from Visual Studio, see How to: Publish an app for Office. To publish an app without using Visual Studio, you can deploy the HTML page for your app and .js files on a web server, and then upload your app manifest file to a network share catalog or App Catalog on SharePoint. Before uploading the manifest file, replace the ~remoteAppUrl token in the DefaultValue attribute of SourceLocation tag to specify the full URL of the default HTML page for your app on the web server where it is hosted.

Show:
© 2014 Microsoft