Pieter van der Westhuizen

How to create Word Apps for Office 365

It’s been close to two years since we’ve discussed the release of Office 2013 and the new web-based object model for Office, called Napa, which allows developers to build Office add-ins using HTML, CSS and JavaScript.

We thought that after we investigated how to create customization for Google Docs and Google Sheets, it is about time we tackle the Napa Office 365 development tools again. We’ll create a Task Pane app for Microsoft Word, similar to the one we created for Google Docs that will allow the user to shuffle either the selected words, sentences or paragraphs in a Microsoft Word document.

Creating an Office App for Word

Before you can start creating and testing your Office App, you need to first provision a Developer site. I won’t go into the steps involved in creating such a site as this article on MSDN does a good job of explaining the necessary steps.

You have two options when creating an app for Microsoft Office, the first is via the Napa development tools inside your browser and the second is using Office Developer Tools for Visual Studio 2013.

Creating a Word app using the Napa development tools

After the Developer site has been provisioned, open it in your browser. You should be presented with the following options:

Creating an app using the Napa development tools

Click on the “Build an app” button. This will redirect your browser to www.napacloudapp.com, then click on the “Add New Project” button in order to create a new App.

Click on the 'Add New Project' button in order to create a new App.

A modal dialog will be shown; prompting you to select the type of app you would like to build. Our app will target Microsoft Word, so select Task pane app for Office from the list.

Select Task pane app for Office from the list.

This will create a project containing all the necessary HTML, CSS and JavaScript files. Because we need the app to run inside Microsoft Word, we have to set this in the project properties. Click on the Properties item in the left hand navigation menu and change the application to launch to Microsoft Word.

Click on the Properties item and change the application to launch to Microsoft Word.

You have a choice to either edit the project via the browser or open the project in Visual Studio by clicking on the “Open in Visual Studio” item in the left-hand navigation bar. This will download and open the project in Visual Studio.

Creating a Word app using Visual Studio 2013

You also have the choice of creating a new app by using Visual Studio 2013. Start by creating a new Apps for Office project, by selecting the project template in Visual Studio.

Select the App for Office project template in Visual Studio.

Select Task pane when prompted to choose which app you’d want to create.

Select Task pane when prompted to choose which app you'd want to create.

We’ll only be targeting Microsoft Word with this app, so only check its checkbox when asked in which Office application your task pane should reflect in.

Check the Word checkbox when asked in which Office application your task pane should appear.

The project template will add all the necessary files needed to create the MS Word app and your Solution Explorer layout will appear, which will look similar to the following:

The Solution Explorer layout

If you’ve opted to create your Word app using the Napa tools, the project layout and files will be exactly the same as when creating the project directly from Visual Studio.

Building the app UI

The Home.html file contains a base layout, which already implements the correct styling for Office. This style is defined inside the Office.css and Home.css files. Add any of your own CSS styles, that you would like to use for the app inside the Home.css file.

The app will be a task pane running inside Microsoft Office Word and will look similar to the following image:

The app will be a task pane running inside Microsoft Office Word.

The UI is created by specifying the following HTML markup inside the Home.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>WordShuffleIt</title>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.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.1/hosted/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>
    <!-- Page content -->
    <div id="content-header">
        <div class="padding">
            <h1>The Word Shuffler</h1>
        </div>
    </div>
    <div id="content-main">
        <div class="padding">
            <p><strong>This app shuffles your selection in MS Word.</strong></p>
            <p>Please select how you would like to shuffle the current selection:</p>
            <p>
                <input type="radio" name="shuffleType" value="Words" checked>Words
            </p>
            <p>
                <input type="radio" name="shuffleType" value="Sentences">Sentences
            </p>
            <p>
                <input type="radio" name="shuffleType" value="Paragraphs">Paragraphs
            </p>
            <button id="do-stuff">Shuffle It!</button>
        </div>
    </div>
</body>
</html>

In the Html mark-up, we added a short instruction text, three radio buttons and a button.

Shuffling the selected text using JavaScript

We define all our app logic inside the Home.js file. The project template created some initial boilerplate code inside this file. The most important item for this app is the initialize function. This function runs as soon as the app is opened inside Word.

Add a click handler for the do-stuff button which will invoke the getDataFromSelection function when the user clicks the button.

Office.initialize = function (reason) {
    $(document).ready(function () {
        app.initialize();
        $('#do-stuff').click(getDataFromSelection);
    });
};

The getDataFromSelection function in turn will check which radio button is selected and store the value inside the shuffleType variable. We’ll then get the currently selected text inside MS Word by calling the getSelectedDataAsync function, the selected text is then passed into the shuffleSelectedText function.

function getDataFromSelection() {
    var shuffleType = $('input[name=shuffleType]:checked').val();
    Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
		function (result) {
		    if (result.status === Office.AsyncResultStatus.Succeeded) {
		        shuffleSelectedText(result.value, shuffleType);
		    } else {
		        app.showNotification('Error:', result.error.message);
		    }
		}
	);
}

The shuffleSelectedText function will split the selected text based on the type of shuffle the users selected, which could be words, sentences or paragraphs. The Office apps object model does not provide a function to determine whether paragraphs are selected, so we’ll simply split the selected text by the newline character. After the selected text is split according to the user’s selection, we pass it into the shuffle function in order to return an array with the shuffled selection.

We then override the selection with the shuffled text by using the setSelectedDataAsync function and show a notification to the user indicating how many words, sentences or paragraphs where shuffled.

The code for the shuffleSelectedText and shuffle function is as follows:

function shuffleSelectedText(text, shuffleType) {
    var shuffledArray;
    var shuffledText = "";
    if (shuffleType == "Words") {
        shuffledArray = shuffle(text.split(' '));
        for (var i = 0; i < shuffledArray.length; i++) {
            shuffledText += shuffledArray[i] + ' ';
        }
    } else if (shuffleType == "Sentences") {
        shuffledArray = shuffle(text.match(/[^\.!\?]+[\.!\?]+/g));
        for (var i = 0; i < shuffledArray.length; i++) {
            shuffledText += shuffledArray[i];
        }
    } else if (shuffleType == "Paragraphs") {
        shuffledArray = shuffle(text.split(/\r\n|\r|\n/g));
        for (var i = 0; i < shuffledArray.length; i++) {
            shuffledText += shuffledArray[i] + '\r\n';
        }
    }
    Office.context.document.setSelectedDataAsync(shuffledText);
    app.showNotification("Shuffled " + shuffledArray.length + " " + shuffleType);
}
 
function shuffle(array) {
    var currentIndex = array.length
      , temporaryValue
      , randomIndex
    ;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
 
    return array;
}

To test the app, build and run the project. Microsoft Word will open with the app loaded inside a task pane and will resemble the following screenshot:

The Word Shuffler app loaded inside a task pane in Microsoft Word.

Thank you for reading. Until next time, keep coding!

Available downloads:

Word Shuffler app

9 Comments

  • Stan says:

    Hi Pieter, thanks for the nice article! Have you tried to deploy the app created by VS onto actual sharepoint/Office365 site? Somehow I can’t figure out how to package it correctly lol. Maybe there’s no way to do that.

  • Pieter van der Westhuizen says:

    Hi Stan,

    To be honest with you, I have not published an app to a non-development SharePoint site.
    However, it does look like MSDN have a fairly decent guide on deploying Office Apps. Take a look at it here and let us know if you got it working!

    Good luck and thanks for your comment!

  • John says:

    Is it possible to put the controls in the ribbon bar like in VSTO?
    Also, is data binding possible in the task pane?

  • Pieter van der Westhuizen says:

    Hi John,

    Changes to Office Add-ins were announced at Build this year, where a new feature called add-in commands was unveiled, which will allow developers to add buttons to ribbons. You can read more about it here

    As for your question about databinding…you should probably be able to accomplish something along those lines using a framework like AngularJs.

    Hope this helps!

  • Sampath says:

    i am unable to select word as an add in … i am unable to select word task pane as it is asking me for visual studio .. i tried to install but no use .. can u please suggest me solution

  • Dmitry Kostochko (Add-in Express Team) says:

    Hello Sampath,

    To develop an add-in, you do need to have Visual Studio installed. If you have run into some other problem, please provide more details.

  • Milias says:

    can you help me how to get data from sharepoint online lists

  • Milias says:

    office app how to connect home.js with sharepoint online can you help me

  • Andrei Smolin (Add-in Express Team) says:

    Hello Milias,

    We can’t help you as we don’t provide any support for web versions of Office 365 applications. I suggest that you find a suitable forum or google for a solution.

Post a comment

Have any questions? Ask us right now!