Welcome to MSDN Blogs Sign in | Join | Help

Microsoft Excel

The team blog for Microsoft Excel and Excel Services.
Excel Services part 7: Sample application with Excel Web Services

Last week I gave an overview of Excel Web Services and the types of scenarios these web services will enable.  This post, I would like to show you an example.  Let’s look at implementing a browser-based mortgage calculator. The application is simple, but still demonstrates a few key Excel Services concepts:

  • Using a server-side Excel spreadsheet calculation as part of another application.
  • Writing custom interactive UI around the Excel Calculation Service.
  • Protecting and maintaining proprietary business models, while still providing your users the ability to provide their own inputs and receive answers.  No need to recode an Excel model just to protect it.

The sample app
For this example, I am going to walk through how to build a tool for calculating a mortgage return, much like something you would find on a bank’s website).


(Click to enlarge)

The example here is a simplified version of such a tool, with one twist: the entire calculation is done on the server by an Excel workbook, and not by a function written in a programming language.  As far as the users are concerned, the tool does not appear to be related to Excel; it is just an ordinary interactive web form.

A user can type in the mortgage amount, mortgage period length, and interest rate, click Calculate, and see the resulting monthly payment appear on the form.


(Click to enlarge)

So what’s going on here?  Behind the scenes, the web page uses an Excel Web Services session to load the mortgage calculator workbook, set its parameter cells to the values provided by the user, and retrieve the calculated result from the appropriate formula cell.

(Note - the UI for this application is a SharePoint web part.  An application does not need to be in SharePoint, however – the user interface could be anything that can “speak” web services.)


The workbook
Here is the Excel workbook with the mortgage calculating model – mortgagecalc.xlsx.


(Click to enlarge)

We can see that the model, in this case, is actually not a whole lot of proprietary information: the entire calculation is done in cell C8 by using a single Excel formula, PMT (but the web site users don’t have to know that).

We can also see that cell C8 has a name – “Payment”.  Similarly, the three input parameter cells C4, C5 and C6 each also have a name (though they don’t have to be named cells to be exposed by Excel Web Services - they can use cell references too).  This enables better isolation between the workbook and the code around it; the code refers to the sheet only through named ranges, so the model can later be freely edited and laid out in any way that the author sees fit, as long as the parameter and result names remain intact.  Here is the “Manage Name” dialog in Excel “12”, where we can see the entire set of names in the workbook.


(Click to enlarge)

The workbook is published to a server document library (see my discussion about publishing for more details).

The code
Let’s look at the application code. For brevity, I am only going to discuss the parts of the code that have to do with running the Excel Web Service session; this code is all within one method, which is called from the Calculate button’s click handler. The rest of the code for this application is standard web part code.

private void CalculateUsingWebService() 
{
   Status[] status;
   string sessionId = null;

   // Step 1: Instantiate the web service
   XlMortgageCalcWebPart.Es.ExcelService es = new XlMortgageCalcWebPart.Es.ExcelService();

   // Step 2: Set web service link
   es.Url = this.ExcelWebServiceUrl;
   // Step 3: Set credentials
   es.Credentials = System.Net.CredentialCache.DefaultCredentials;

   // Step 4: Start the session
   try
   {
    sessionId = es.OpenWorkbook(this.MortgageCalculatorWorkbookUrl, String.Empty, String.Empty, out status);
   }
   catch
   {
    sessionId = null;
   }
   if (sessionId == null)
   {
    _lblError.Text = "Error opening workbook.  Please make sure that the correct MortgageCalculatorWorkbookUrl and ExcelWebServiceUrl are specified in the Web Part Properties.";
    this.Controls.Clear();
    this.Controls.Add(_lblError);
    return;
   }

   // Step 5: Set parameters
   es.SetCellA1(sessionId, "SimpleCalculator", "MortgageAmount", _txtMortgageAmount.Text.Trim());
   es.SetCellA1(sessionId, "SimpleCalculator", "MortgageLength", _txtMortgageLength.Text.Trim());
   es.SetCellA1(sessionId, "SimpleCalculator", "InterestRate", _txtInterestRate.Text.Trim());

   // Step 6: Get result
   object o = es.GetCellA1(sessionId, "SimpleCalculator", "Payment", true, out status);
   if (o != null)
   {
      _lblTotal.Text = Convert.ToString(o);
   }
   else
   {
      _lblError.Text = "Error getting total value from workbook.";
      this.Controls.Clear();
      this.Controls.Add(_lblError);
    return;
   }

   // Step 7: End the session
   status = es.CloseWorkbook(sessionId);
  }

Let’s go over the main steps in this piece of code. To see a full description of Excel Web Services methods and functionality, please look at last week’s post – Building applications with Excel Web Services.

  1. Instantiate the web service: Create an instance of the ExcelService object. This object is generated by Visual Studio when a developer adds a web reference to the web service’s asmx file. As you can see, it is generated in the application’s namespace.
  2. Set web service link: Set the URL to the web service.
  3. Set credentials: In this case, we set the credentials that are passed to the web service for authentication to DefaultCredentials, meaning that the application’s own credentials are used.
  4. Start the session: Call OpenWorkbook, passing the path to the mortgage calculator Excel workbook (a web part property in our case), and receiving a sessionId. This sessionId is subsequently used in other Web service calls, to identify our session.
  5. Set parameters: Call SetCellA1 to set the three parameter cells to the values that the user typed into the web part form. We can see how named ranges are used, as opposed to direct cell references, to make the code robust – insensitive to layout changes in the workbook.
  6. Get result: Call GetCellA1 to get the calculation result, the “Payment” named range. The sample workbook was set to be automatically recalculated, so as soon as all the parameters are set, we can immediately expect the result to be available. In some cases, automatic recalculation is turned off while authoring the Excel workbook; a call to Calculate is then necessary at the point in the code where we want to tell the Excel Calculation Service to explicitly calculate formulas.
  7. End the session: Call CloseWorkbook to end the session. This call tells the Excel Calculation Service that we are done with this session, and all resources that were associated with our session can be released.

That’s it - with 7 lines of code and some exception handling, we have integrated an Excel spreadsheet calculation on the server with our mortgage calculator application. The application provides the custom user interface; Excel Services process the Excel spreadsheet model; and the Excel Web Service enables tying it all together.

While this was just a simple example, you can envision much more complex calculations represented by spreadsheets that you can now call from an application.  The calculations can be provided as a service to applications, while the model is safely hidden and secured.

PS Edited to fix a screen-shot problem.

 

Posted: Monday, November 21, 2005 2:01 PM by David Gainer
Filed under:

Comments

Jim Cone said:

I know, I know, it is only an example, but the payment on a $100,000 loan at 5.2 % over 30 years is...$549.11
# November 21, 2005 6:55 PM

Harlan Grove said:

Jim Cone...
|I know, I know, it is only an example, but the
|payment on a $100,000 loan at 5.2 % over 30
|years is...$549.11

Guess web services are more difficult to write (or write about) than they seem.

That or the next set of documentation will be a doozy.

Unlikely the sample output was produced by the web service, at least not by the workbook shown later. How many other screen shots in this blog have been make-believe?
# November 22, 2005 2:48 AM

Jan Karel Pieterse said:

Harlan:

> How many other screen shots in this blog
> have been make-believe?

I understand your scepticism.
Although being in the beta program ties me to an NDA, since everything published here is publicly available I can safely tell you: none.
# November 22, 2005 3:11 AM

Harlan Grove said:

This is a very good example of what not to do via Excel. A simple mortgage calculation could be done in a client-side script with a single expression using the values from the 3 inputs.

pmt = principal / ((1 - (1 + rate / 1200) ^ -(years * 12)) / (rate / 1200))

7 lines of code plus exception handling seems excessive. I realize this is just an example, but why is Excel as a platform for web services a good idea? There may be a lot of absurdly oversized spreadsheet applications, but is that a good reason to make them into black box evaluators for web services?

I suppose it's old fashioned to bemoan using multimegabyte workbooks for calculations that could be implemented in a few hundred lines of FORTRAN or C/C++ (or maybe even C# if there's some mechanism to access BLAS, LAPACK, LINPACK and EISPACK). Not every good interactive tool makes a good background tool.
# November 22, 2005 3:47 AM

John Greenan said:

Just for what it's worth, in response to Harlan:

Maybe the usage for this is firms where there has been big investment in spreadsheets and very little in "proper" software/technology like C++ or Fortran? As for being old fashioned, it's not old fashioned to hear IT people complaining that firms have not invested enough in IT, just predictable and frankly somewhat dull ;-)
# November 22, 2005 6:09 AM

david matusow said:

Off topic question: Will the new Excel 12 UI make Cut and Copy work like it does on all other Windows applications or will Cut items still not be put on the clipboard? (if I perchance want to paste something twice?)
# November 22, 2005 7:01 AM

David Gainer said:

Howdy folks,

Jim, nice catch. The $1,049.11 value was a mistake on our part, which gives me an opportunity to provide an example of the kind of things spreadsheets on the server enable. We use this spreadsheet and code internally for demonstrations. Our demo is roughly like this - we do walk folks through using the form and the show them the spreadsheet behind the calculations. After we have explained the basics and how things work, we open the spreadsheet in Excel 12, add $500 to the final result (a really expensive sales commission, say), save the workbook, and then switch back to the web page and press “Calculate” again, which shows the new value. This shows how easy it is to update the logic in an application – as easy as making the change in Excel and pressing Save. What happened is that the screenshot was generated with the updated spreadsheet (forgot to take the $500 out after the last demo). I have updated the screenshot, thanks for pointing this out.

Harlan, *every* screenshot in this blog (including the one in question in this post) has been produced using either the beta build of Office 12 or a pre-beta build.

Jan Karel, thanks for verifying.

Harlan, John, one thing to keep in mind is that a lot of people who create important models in Excel don’t know how to use C++ or C# or Fortran or Java etc. Currently, if IT needs to protect/lock down/re-use/share those models with customers, they pretty much have to re-develop them, which is costly and often slow due to lack of resources. If they can be put on a centrally managed server running Excel Services, it simplifies the task significantly.

David, no change to copy paste.
# November 22, 2005 8:15 PM

Biff said:

Yikes!

Looks like half the screen is taken up by icons and toolbars.

Not a pretty picture!
# November 22, 2005 8:55 PM

David Gainer said:

Biff, that is optional "chrome". When you just post a spreadsheet and look at it, it looks like this: http://www.isamrad.com/dgainer/s4_11-16-2005.png
# November 22, 2005 9:13 PM

Biff said:

OK, much better!
# November 22, 2005 9:40 PM

Harlan Grove said:

OK, I understand that there may be companies with very large, complicated spreadsheet models that would be a royal PITA to rewrite in a procedural or OO language. However, many of those models may be so large that recalculation is set to manual. If a model requires, say, hundreds of parameters entered in dozens of different areas in the workbook, will Excel Services provide full control over recalculation, i.e., allow the equivalent of manual calculation while loading parameters into the workbook, then provide the equivalent of Application.CalculateFull? In other words, can workbooks be stored in a SharePoint library with Calculation set to manual and recalculated on demand when used as web services?

While I grant that some companies may take the narrow, short term, penny wise pound foolish view that using Excel workbooks as the basis for web services may appear to be a good idea, the thought of a few dozen users each needing their own memory image of a 30MB workbook rather than each having access to a reentrant DLL that itself take up a few hundred KB in memory and only needs a few dozen KB of state information including black box inputs for each client still strikes me as ridiculous.
# November 23, 2005 2:49 PM
New Comments to this post are disabled
Page view tracker