Excel

Revision for “Excel” created on April 15, 2015 @ 18:47:47

TitleContentExcerptRevision Note
Excel
It is possible to integrate .NET code with Microsoft Excel. In the following I will show how create an Excel worksheet that uses <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a>.NET.

To integrate Visual Sudio with .NET, you need Visual Studio 2008 Professional or higher, as well as Microsoft Office 2007 or higher. Please also ensure that during installation of Visual Studio, you have installed the component Visual Studio Tools for Office Runtime. In this tutorial we will be using Visual Studio 2010 Professional with C#.
<h2 id="ExamplesProject">Examples Project</h2>
Instead of following the tutorial below, you can download a project containing the described examples [here <a href="http://redmine.numericalmethod.com/projects/public/repository/show/SuanShu.NET" target="_blank">http://redmine.numericalmethod.com/projects/public/repository/show/SuanShu.NET</a>]. You may also use this project as a starting point for your own application.

The example project for Excel contains some methods that convert between Excel ranges to Vector and Matrix datatypes in <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a>. If you are planning of using <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a> in Excel, it is highly recommended that you look at the examples, to see how this is done.
<h2 id="SettingUptheProject">Setting Up the Project</h2>
First we create a new project. If you have everything set up as in <a href="http://numericalmethod.com/up/suanshu/dotnet/" target="_blank">SuanShu/DotNet</a>, you should be able to create a Project from an Excel Workbook template. Also don’t forget to enter an appropriate name for the project below the template selection.
<a href="http://numericalmethod.com/wp-content/uploads/2015/04/newproj.jpg"><img class="alignnone size-full wp-image-3521" src="http://numericalmethod.com/wp-content/uploads/2015/04/newproj.jpg" alt="newproj" width="1001" height="682" /></a>
On the next screen, simply click ‘OK’.

Having created a new project, you must first add <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a>.NET to the References again. To do this, please follow the instructions in the previous section. This time however, the license file should be located in your ‘My Documents’ folder. An explanation of how to change the directory in which <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a> looks for the license file is given in the Tips and Tricks section.
<h2 id="TheWorksheet">The Worksheet</h2>
Let’s now create a simple example program to demonstrate some simple ways of interacting with the Excel worksheet. In this example we will solve a system of linear equations (of the form Ax = b).

First we will set up our worksheet to hold the input and output of our function. This can be done by editing the worksheet like you would from Excel. Please add the following labels and example numbers:

<a href="http://numericalmethod.com/wp-content/uploads/2015/04/setup1.jpg"><img class="alignnone size-full wp-image-3522" src="http://numericalmethod.com/wp-content/uploads/2015/04/setup1.jpg" alt="setup1" width="511" height="233" /></a>
<a href="http://numericalmethod.com/wp-content/uploads/2015/04/button.jpg"><img class="alignnone size-full wp-image-3523" src="http://numericalmethod.com/wp-content/uploads/2015/04/button.jpg" alt="button" width="344" height="428" /></a>

&nbsp;

We also add a button to trigger the computation. Open the toolbox (if it isn’t already open, press CTRL + W, X) and drag a Button onto the worksheet.

The button can be renamed by changing its ‘Text’ property in the ‘Properties’ dialog, which by default is in the bottom right corner of the screen.

A useful feature is to assign fields names, which we can then reference in the cods. This is done by right clicking the cell and selecting ‘Define Name…’. Let’s call the cells beneath ‘x:’, ‘b:’ and ‘A:’ ‘xStart’, ‘bStart’ and ‘AStart’ respectively. To manage defined names, you can use the ‘Name Manager’ in the Formulas tab.
<a href="http://numericalmethod.com/wp-content/uploads/2015/04/name.jpg"><img class="alignnone size-full wp-image-3524" src="http://numericalmethod.com/wp-content/uploads/2015/04/name.jpg" alt="name" width="360" height="530" /></a>

Pressing F7 will now take you to the code view. To return to the designer view, press SHIFT + F7. As you can see, a method stub for the button has already been created for you. Let’s now insert the code that solves the linear equation.

<a href="http://numericalmethod.com/wp-content/uploads/2015/04/defaultcode.jpg"><img class="alignnone size-full wp-image-3525" src="http://numericalmethod.com/wp-content/uploads/2015/04/defaultcode.jpg" alt="defaultcode" width="572" height="598" /></a>

<h2 id="Coding">Coding</h2>
To simplify the integration of <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a> with Excel we provide a file called SuanShuExcel, which has methods to read and write scalars, vectors and matrices from the worksheet. If you have started your project from scratch, you should add the file to your project.

Having done this, we can solve the linear equation using the following simple code.
<pre class="toolbar-overlay:false show-lang:2 lang:c# decode:true">
private void button1_Click(object sender, EventArgs e) {
// Read b and A starting at the previously named cells bStart and AStart
Vector b = SuanShuExcel.ReadVector(bStart.Row, bStart.Column, this);
Matrix A = SuanShuExcel.ReadMatrix(AStart.Row, AStart.Column, this);

// Precision parameter
double epsilon = 1E-15;

// Solve the linear equation
LinearSystemSolver solver = new LinearSystemSolver(epsilon);
LinearSystemSolver.Solution solution = solver.solve(A);
Vector x = solution.getParticularSolution(b);

// Write the result starting at the previously named cell xStart
SuanShuExcel.WriteVector(x, xStart.Row, xStart.Column, this);
}
</pre>
If you are unsure about what any of these do, please refer to the XML comments in SuanShuExcel or the documentation below for <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a>.
<h2 id="RunningtheProject">Running the Project</h2>
You are now ready to run the project by pressing F5, as you would for a normal Visual Studio project. When reopening the project, please make sure you open the (.sln) Visual Studio solution and not the (.xlsx) worksheet.

After building a ‘Release’ version (see image below) of a solution, it can then be run by opening the worksheet in the bin\Release folder.

<a href="http://numericalmethod.com/wp-content/uploads/2015/04/release1.jpg" target="_blank"><img class="alignnone size-full wp-image-3526" src="http://numericalmethod.com/wp-content/uploads/2015/04/release.jpg" alt="release" width="118" height="22" /></a>
<h2 id="AnotherExample">Another Example</h2>
Another example (matrix multiplication) can be found in the examples project. It demonstrates how to automatically recompute the result when the worksheet is changed, how to write matrices and how to use the this.Cells and this.Range classes to clear a range of cells.
<h2 id="UsingUsedDefinedFunctionsinExcel">Using Used Defined Functions in Excel</h2>
Instead of linking a Visual Studio project with an Excel worksheet, you can also define User Defined Functions, which can be used in formulae, much like Excel’s built-in functions. We provide a project that you can use as a starting point to develop your own UDFs. If you want to create a similar project from scratch or are unsure how this project was created, there is a thorough explanation <a class="ext-link" href="http://blogs.msdn.com/b/gabhan_berry/archive/2008/04/07/writing-custom-excel-worksheet-functions-in-c_2d00_sharp.aspx"><span class="icon">​</span>here</a>.

The project is an ‘Automation Add-In’, enabling Excel to call functions on COM objects from cells on the worksheet. There are other ways of defining UDFs via .NET, but this is the officially supported and for our purposes simplest way.
<h3 id="ClassStructure">Class Structure</h3>
<a href="http://numericalmethod.com/wp-content/uploads/2015/04/addin.jpg"><img class="alignnone size-full wp-image-3527" src="http://numericalmethod.com/wp-content/uploads/2015/04/addin.jpg" alt="addin" width="530" height="451" /></a>

The interop protocol between .NET and Excel is called Component Object Model (COM). COM only looks at interfaces rather than base classes, so for COM to recognise our methods we first have to perform the following steps:
<ol>
<li>We define an interface containing definitions of our UDFs</li>
<li>Both the interface and the class need the ComVisible(true) attribute</li>
<li>Furthermore our class needs to have Guid via the Guid attribute (you can generate Guids using the Tools->Create Guid tool in Visual Studio) and have its interface specified via ComDefaultInterface(typeof(_our_interface)). COM doesn’t care whether you implement the interface in the C# sense, but doing so helps ensuring you implement all required methods from the interface.</li>
<li>We add code that adds the location of your dll to the registry. This code can just be copied to any new classes as you create them.</li>
</ol>
If you add a new file to the project you have to remember to do all these things or the UDF will likely not be found in Excel.
<h3 id="ConvertingbetweenSuanShuandCOMcompatibleobjects">Converting between <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu</a> and COM compatible objects</h3>
Like for the previous example we provide a class that converts between <a href="http://numericalmethod.com/up/suanshu/" target="_blank">SuanShu’s</a> Matrix and Vector objects and the objects that are passed by COM. The class can be found in the SuanShuAddin example project as SuanShuAddin.cs.
<h3 id="UsingtheUDFs">Using the UDFs</h3>
I will explain how to use our define UDFs by using matrix multiplication as an example.

To build the project and register the Add-In, Visual Studio must be run with Administrator privileges (in Windows Vista or later this is done by right clicking the shortcut and clicking ‘Run as Administrator’). After building the project, we need to load the UDF in Excel. To do so we first open the ‘Add-In Manager’. To do this in Excel 2010, open the options dialog from the file tab and in the Add-Ins section under ‘Manage’ select ‘Excel Add-Ins’ and press Go.

In the Add-Ins window, press ‘Automation’ and in the ‘Automation Servers’ window find the class you want to load, select it and press OK twice. It’s name will be the project name followed by the class name, e.g. SuanShuAddin.SuanShu.

If the add-in does not appear, it may be because Visual Studio Tools for Office is not activated. A simple way to check this is to open the SuanShuExcel (not the add-in) project and see if you can successfully build and run it.

<a href="http://numericalmethod.com/wp-content/uploads/2015/04/automation.jpg"><img class="alignnone size-full wp-image-3528" src="http://numericalmethod.com/wp-content/uploads/2015/04/automation.jpg" alt="automation" width="619" height="444" /></a>

After having done that, you can use the UDFs as follows:
<ol>
<li>Select the range that you want the result to be written to (or the cell if the output is just a single number).</li>
<li>In the formulas tab, click ‘Insert Function’.</li>
<li>Under ‘Category’, select one of the Add-Ins you just loaded (each interface is a separate Add-In).</li>
<li>Select the function you would like to insert and press OK.</li>
<li>Select the input arguments.</li>
<li>If the output is just a single number, click OK. If it is a vector or matrix, press CTRL+Shift+Enter.</li>
</ol>

<a href="http://numericalmethod.com/wp-content/uploads/2015/04/udf1.jpg"><img class="alignnone size-full wp-image-3529" src="http://numericalmethod.com/wp-content/uploads/2015/04/udf1.jpg" alt="udf1" width="472" height="412" /></a>
<a href="http://numericalmethod.com/wp-content/uploads/2015/04/udf2.jpg"><img class="alignnone size-full wp-image-3530" src="http://numericalmethod.com/wp-content/uploads/2015/04/udf2.jpg" alt="udf2" width="704" height="520" /></a>

<h3 id="ExampleSpreadsheet">Example Spreadsheet</h3>
We have provided an example spreadsheet (addin_example.xlsx) that you can use to check whether the add-in is working correctly. However you will still need to follow the instructions for building and loading the add-in for the formula in the spreadsheet to work.



Old New Date Created Author Actions
April 15, 2015 @ 18:47:47 webmaster
April 15, 2015 @ 18:47:39 [Autosave] webmaster
April 14, 2015 @ 07:15:23 sanjay
April 13, 2015 @ 10:32:47 sanjay
April 13, 2015 @ 10:32:02 [Autosave] sanjay
April 13, 2015 @ 08:28:18 sanjay