Open the add-in homepage
Locate and open the homepage for the add-in: Home.html.
Add a script reference
Immediately after the reference to Office.js in the portion of the page, add the following script reference to the Excel JavaScript API beta CDN:
Note: Eventually the all Excel JavaScript APIs will be merged into the single Office.js file so this step will not be necessary, but in the 1.2 API preview timeframe it is required as an extra step.
Update the UI for the add-in
Locate the section of the page within the home.html file.
Replace the contents of the with the following markup (copy from below and paste):
vi. Insert Data Inseart Data, add a table and adjust layout Sort Sort my data based on transaction date Filter Only show my transtions in fuel and education Report Create a report on my spending and Protect the report
Add the Business Logic
The next step is to code the business logic for the add-in. Locate the Home.js file. Remove all the sample code except the add-in initialization code so all that is left is the following: (function () { "use strict"; // The initialize function must be run each time a new page is loaded. Office.initialize = function (reason) { $(document).ready(function () { // Initialize the FabricUI notification mechanism and hide it var element = document.querySelector('.ms-MessageBanner'); messageBanner = new fabric.MessageBanner(element); messageBanner.hideBanner(); // attach click handlers to the workbook // TODO-1 // TODO-2 // TODO-3 // TODO-4 return; }); } // Helper function for treating errors function errorHandler(error) { // Always be sure to catch any accumulated errors that bubble up from the Excel.run execution showNotification("Error", error); console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } } // Helper function for displaying notifications function showNotification(header, content) { $("#notificationHeader").text(header); $("#notificationBody").text(content); messageBanner.showBanner(); messageBanner.toggleExpansion(); } })();
Add a function that will add data
Replace the comment // TODO-1 with the following jQuery code that creates a click event handler on one of the buttons in the home.html page you added previously: $('#insertData').click(insertData);
Add a function
Add the following function (copy from below and paste). Notice how the code in this function is very different from the code in the previous exercises. The Excel JavaScript API uses a context (Excel.run()) to allow you to batch multiple operations (such as context.workbook.worksheets.add()) that will be sent to the hosting Excel client application for processing at one time using the context.sync() method: function insertData() { Excel.run(function (ctx) { // Get the current worksheet var sheet = ctx.workbook.worksheets.getActiveWorksheet(); //Rename the current Worsheet to Data sheet.name = "Data"; //Insert Data var range = sheet.getRange("A1:E11"); range.values = [[ "Date", "Merchant", "Category", "Sub-Category", "Amount"], [ "01/12/2014", "WHOLE FOODS MARKET", "Merchandise & Supplies", "Groceries", "84.99" ], [ "01/13/2014", "COSTCO GAS", "Transportation", "Fuel", "52.20" ], [ "01/13/2014", "COSTCO WHOLESALE", "Merchandise & Supplies", "Wholesale Stores", "163.67" ], [ "01/13/2014", "ITUNES", "Merchandise & Supplies", "Internet Purchase", "9.83" ], [ "01/13/2014", "SMITH BROTHERS FARMS INC", "Merchandise & Supplies", "Groceries", "21.45" ], [ "01/14/2014", "SHELL", "Transportation", "Fuel", "44.00" ], [ "01/14/2014", "WHOLE FOODS MARKET", "Merchandise & Supplies", "Groceries", "17.98" ], [ "01/15/2014", "BRIGHT EDUCATION SERVICES", "Other", "Education", "59.92" ], [ "01/15/2014", "BRIGHT EDUCATION SERVICES", "Other", "Education", "59.92" ], [ "01/17/2014", "SMITH BROTHERS FARMS INC-HQ", "Merchandise & Supplies", "Groceries", "21.45" ]]; //Autofit row height and column width range.getEntireColumn().format.autofitColumns(); range.getEntireRow().format.autofitRows(); // Add a table var table = ctx.workbook.tables.add("Data!A1:E11", true); return ctx.sync().then(function () { }); }).catch(function (error) { console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } }); }
Add a sort function
Now add functionality to sort data based on transaction date: Go back to the Office.initialize statement and replace the comment // TODO-2 with the following jQuery code that creates a click handler for the button that will add a range of unformatted data to the current worksheet: $('#sort').click(sort);
Add another function.
Copy and paste the following into the statement function sort() { Excel.run(function (ctx) { var sheet = ctx.workbook.worksheets.getActiveWorksheet(); // Only Sort the range that has data var sortRange = sheet.getRange("A1:E1").getEntireColumn().getUsedRange(); // Apply sorting on the first column and in descending order sortRange.sort.apply([ { key: 0, ascending: false, }, ]); return ctx.sync().then(function () { }) }).catch(function (error) { console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } }); }
Add a filter function
Then we add functionality to filter data. We only want to focus on the transaction in the sub-category of Fuel and Education. Go back to the Office.initialize statement and replace the comment // TODO-3 with the following jQuery code that creates a click handler for the button that will add a range of unformatted data to the current worksheet: (copy and paste the filter into place) $('#filter').click(filter);
Add another function
Next, add the following function. Notice how the code works with ranges in a similar way to the last function, but this one assigns some formats to the range's numberFormats property (copy and paste from below): function filter() { Excel.run(function (ctx) { var sheet = ctx.workbook.worksheets.getActiveWorksheet(); var table = sheet.tables.getItemAt(0); //Apply a value filter on the 4th column, which is sub-category. We want to focus on transactions in the category of Fuel and Education var filter = table.columns.getItemAt(3).filter; filter.applyValuesFilter(["Fuel","Education"]); return ctx.sync().then(function () { }) }).catch(function (error) { console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } }); }
Add the ability to use Excel formulas and charts
Now, we add functionality to use Excel formulas and charting to generate a report and then protect the report from editing. Here we first create a new sheet named "Summary", then create a summary table with total spendings based on Category. We then add a chart to visualize the data. Finally we protect the sheet from further changes. Go back to the Office.initialize statement and replace the comment // TODO-4 with the following jQuery code that creates a click handler for the button that will add a range of unformatted data to the current worksheet (copy and paste from below): $('#report').click(report);
Add a report function
Notice how the code works with ranges in a similar way to the last function, but this one assigns some formats to the range's numberFormats property (copy and paste from below): function report() { Excel.run(function (ctx) { //Add a new worksheet var sheet = ctx.workbook.worksheets.add("Summary"); //Activate the worksheet sheet.activate(); // Use Excel formulas to calculate the total spending based on categories var sumRange = sheet.getRange("A1:B6"); sumRange.values = [['Category', 'Total'], ['Groceries', '=SUMIF( Data!D2:D100, "Groceries", Data!E2:E100 )'], ['Fuel', '=SUMIF( Data!D2:D100, "Fuel", Data!E2:E100 )'], ['Wholesale Store', '=SUMIF( Data!D2:D100, "Wholesale Stores", Data!E2:E100 )'], ['Internet Purchase', '=SUMIF( Data!D2:D100, "Internet Purchase", Data!E2:E100 )'], ['Education', '=SUMIF( Data!D2:D100, "Education", Data!E2:E100 )']]; //Add a Table ctx.workbook.tables.add("Summary!A1:B6", true); // Add a pie chart var chartRange = sheet.getRange("A1:B6"); var chart = ctx.workbook.worksheets.getItem("Summary").charts.add("Pie", chartRange); //Update the chart title chart.title.text = "Spending based on catagory"; // Protect the report from editing sheet.protection.protect(); return ctx.sync().then(function () { }) .then(ctx.sync); }).catch(function (error) { console.log("Error: " + error); if (error instanceof OfficeExtension.Error) { console.log("Debug info: " + JSON.stringify(error.debugInfo)); } }); }
Deploy the Excel add-in to the local Excel client
Select the ExpenseReport project within the Solution Explorer tool window. Within the Properties window, set the Start Action selector to Office Desktop Client and press F5 to start the project.
Visual Studio will launch the Excel desktop client and create a new Excel workbook.
Launch the add-in
Launch your add-in by clicking the Show Taskpane button on the Ribbon. This button is defined in your add-in manifest. You can change the label if you want by edditing the manifest.xml file in your project.
Click the Insert Data button
On the taskpane, click the button Insert Data.
Notice how Excel update the worksheet name to "Data", inserted my transaction data and added a table on top of my data.
Click the Sort button
Click the button Sort.
Notice how Excel sorted my transactions based on date, the latest transaction is on top now.
Click the Filter button
Click the button Filter.
Notice how Excel filtered my transactions based on sub-category, now only transactions under Education and Fuel are shown.
Click the Report button
Click the button Report. Congratulations! You've now written an Excel add-in that uses the new Excel JavaScript API.
Notice how Excel summarized my transactions with formulas and created a pie chart to visualize my spending.
No comments:
Post a Comment