Microsoft Office Excel is the most frequently-used Microsoft application and one of the leading spreadsheet programs available. A spreadsheet program is a program that uses a huge grid to display data in rows and columns. The spreadsheet program can then be used to do calculation, data manipulation, and various similar tasks, against this data.
Microsoft Office Excel is one of the powerful Office tools that provides uncomplicated data management. It is loaded with features such as graphing, charting, pivot tables, and calculation. Even though Excel is loaded with numerous features for users, there may be some functionality that cannot be achieved by using the standard Microsoft Excel environment. In Microsoft Office Excel 2007, automation is a great mechanism for populating business documents (for example, reports) with data from backend system. This can be achieved by using VSTO 3.0 and Visual Studio 2008. Microsoft Office Excel 2007 is more programmable than ever before with support for Visual Studio Tools for Office.
VSTO is aimed at Microsoft Office Excel users who want to develop Excel-based applications for other Microsoft Office Excel users. VSTO 3.0 is shipped with all of the newly-enhanced Excel objects, including improved features for building Microsoft Office based solutions.
VSTO 3.0 is loaded with new features, including support for Windows form controls from within Microsoft Office tools customization. It provides the support for using .NET frameworks, objects and classes for Microsoft Office tools customization. For example, System.Data is the .NET frameworks object that can be used inside the Excel solution to process database operations. This new feature is tightly integrated with the Visual Studio 2008 IDE and gives you the comfort of design time customization of Excel documents for data display and UI customization.
Similar to other Microsoft Office Tools, with Microsoft Office Excel 2007 customization using VSTO 3.0, you have two levels of customization— document-level customization and application-level customization. Document-level customization is a solution created for document-level programming and is specific to the document that is part of that particular solution. Application-level customization is a solution created for application-level programming and is specific to the application, and therefore common to all documents based on that application.
In a simple Hello World demonstration, let’s learn about the document level customization approach. We’ll step through a simple task, showing how to create an Excel document that will display a Hello World message on startup.
Hello World example using Visual Studio 2008
- Open Visual Studio 2008, and create a new Excel 2007 Workbook project.
- Select New Project. Under Office select 2007, and then select the Excel 2007 Workbook template and name the project ExcelHelloWorld, as shown in the following image:
- The document selection dialog box is displayed. At this point, you need to choose the template for your design. In this example, you select a new blank template and click on the OK button. Refer to the following screenshot:
The solution will be created with all of the supporting files required for our development of an Excel solution. Each solution is created with three worksheets, with default names: Sheet1, Sheet2, and Sheet3 for the workbook you’re going to customize , as shown in the following image. The number of sheets in a new workbook depends on the settings in Excel. The following image also shows you the Excel-supported controls, placed on the leftmost side of the Visual Studio 2008 toolbox panel. You can also see the visual representation of Excel 2007 inside Visual Studio 2008.
- Let’s write our Hello World message in a cell when we load the Excel 2007 document. Write the following code inside the ThisWorkbook.cs file.
// The Startup event of workbook in our Excel solution
// Startup event common to all Office application
// Startup event will be fired at the start of the application
private void ThisWorkbook_Startup(object sender,
System.EventArgs e)
{
// Creating the instance of active WorkSheet of Excel Document
Excel.Worksheet AuthorWorkSheet = ThisApplication.ActiveSheet
as Excel.Worksheet;
// Get the range using number index through Excel cells
by setting AuthorExchange to an Excel range object starting at
(1,1) and ending at (1,1)
Excel.Range AuthorExcelRange = ThisApplication.
get_Range(AuthorWorkSheet.Cells[1, 1],
AuthorWorkSheet.Cells[1, 1]);
// Setting the value in the cell
AuthorExcelRange.Value2 = "Hello! this is my VSTO program for
Excel 2007";
}The following screenshot results after adding and executing the preceding code:
Manipulation
Microsoft Office Excel is one of the most comprehensive data management tools for all kinds of users. It is a tool that can be easily understood and quickly learnt. The most important feature of Microsoft Office Excel is its capability to manipulate data from different sources.
Excel is one of the most powerful and user-friendly data manipulation applications. You could use Excel to predict what’s ahead for your business by creating detailed financial forecasts. This powerful application has pivot table functionality that allows you to drop in your data and rearrange it to answer all kinds of business data analysis type questions. Excel helps you to build various useful analytical tools such as your monthly sales report and product sales growth analysis more easily and flexibly. Excel offers you formulae and functions that will help you to perform complex financial calculations without any manual errors. Excel can provide you with a graphical presentation of your business data by using charts and graphs.
Want to know your growth levels for a specific product sales range? Check which parts of your business are performing worse? The pivot table provides more information from your business in depth.
Every application in this computer world works with data. The data can be in any form and can belong to different sources. The key question for data management is where to place the data. You manage the data in two ways: data managed outside the program and data managed inside the program. The data managed outside the program includes data managed in a database, a file system, and so on. Data managed inside the program includes data in different worksheets within the workbook, embedded images, and so on.
Data manipulation
For users who are not satisfied with the default features in Microsoft Office Excel, VSTO programming makes Excel more flexible, and provides a development tool for the creation of custom solutions for data manipulation and data analysis.
Custom programming using VSTO 3.0 improves most part of the Microsoft Office Excel solution. Custom programming using VSTO 3.0 provides a wide range of advantages, including saving time by automating most of the frequently-performed tasks, reducing errors due to manual operations, as well as enforcing standards for data processing, and building the capability to seamlessly integrate with other applications seamlessly.
Reading worksheet cells
There are many ways to manipulate data and write to the cells in an Excel worksheet. Let’s see some of these ways. We can read worksheet cells directly through the Cells property of the sheets, rows, and columns, and can set a value directly by using the cell’s row and column index. Open Visual Studio 2008 and create a new Excel solution. Refer to the previous example for full instructions of how to do this. Write the following code inside the ThisWorkbook.cs file. In this sample explanation, you are writing data into the worksheet by using the Cells object.
// The Startup event of workbook in our Excel solution
private void ThisWorkbook_Startup(object sender,
System.EventArgs e)
{
// Set value for Cells row and column index
// Text data in Sheet1 cells
Globals.Sheet1.Cells[3, 3] = "Set my data";
}
We can also read the worksheet and write data to the cells by using the Range object. In this case, you are creating the range and setting the text data for the range in the Excel worksheet.
Open Visual Studio 2008 and create a new solution, as before. Write the following code inside the ThisWorkbook.cs file . In this demonstration, you read the worksheet through the range of cells and set the value by reading through cell ranges.
private void ThisWorkbook_Startup(object sender,
System.EventArgs e)
{
// Setting value in ExcelSheet cells through reading range object
Excel.Range AuthorExcelSheetRange = Globals.Sheet1.Range["A2",
"B2"];
// Text data for the range A2 to B2
AuthorExcelSheetRange.Value2 = "Set my data";
}
Let’s see a demonstration of how to read data from an external data file and display this inside our Excel cells. In this demonstration, you will see how the data from the text (.txt) file is displayed in the spreadsheet.
Opening a text file as a workbook using VSTO
We’ll now see how to open the text file as a workbook by using VSTO and C# programming. This saves time and makes the user more comfortable in accessing the text file while processing the data. Open Visual Studio 2008 and create a new solution, as before. Write the following code inside the ThisWorkbook.cs file:
// Opening Text file as workbook
private void ThisWorkbook_Startup(object sender,
System.EventArgs e)
{
// In the workbook objects, file path as parameter in Opentext
property this.Application.Workbooks.OpenText(@"C:TechBooks.txt",
// Value 1 is, the row from which it will read data in the text
file missing, 1,
// Checks for delimits for text parsing
Excel.XlTextParsingType.xlDelimited,
// Text Enumeration value
Excel.XlTextQualifier.xlTextQualifierNone,
missing, missing, missing, true, missing, missing, missing,
missing, missing, missing, missing, missing, missing);
}
Connecting with Microsoft SQL Server 2008 database
Microsoft SQL Server 2008 is a relational database management system developed by Microsoft Corporation. Microsoft SQL Server is used to manage a huge volume of data along with relation and Metadata information for this data. VSTO provides support for manipulating the data from your database inside Excel using ADO.NET classes.
The preceding figure demonstrates how an Excel 2007 object is used to interact with the Microsoft SQL Server database. Let’s see how to connect with a relational database management system, retrieve data from the database, and finally display it in our Excel spreadsheet. This demonstration shows you how to retrieve data from a Microsoft SQL Server 2008 database and place the retrieved data into the worksheet cells.
Open Visual Studio 2008 and create a new solution, as usual. Write the following code inside the ThisWorkbook.cs file.
// Namespace for SQL Server connection
using System.Data.SqlClient;
// Startup event of the workbook
private void ThisWorkbook_Startup(object sender,
System.EventArgs e)
{
// Opening SQL connection for Microsoft SQL Server 2008
// WINNER the database server contains the databse called Products
SqlConnection MySQLConnection = new SqlConnection(@"Data
Source=WINNER;Initial Catalog=Products;
Integrated Security=True");
// Passing SQL command text
SqlCommand MySQLCommand = new SqlCommand("SELECT * FROM
Books", MySQLConnection);
MySQLConnection.Open();
// SQL reader to read through data from Database
SqlDataReader MySQLReader = MySQLCommand.ExecuteReader();
// Get the active sheet of current application
Excel.Worksheet MyWorkSheet = this.Application.ActiveSheet as
Excel.Worksheet;
// Header for the columns set in the Value2 properties
((Excel.Range)MyWorkSheet.Cells[1, 1]).Value2 = "Book Name";
((Excel.Range)MyWorkSheet.Cells[1, 2]).Value2 = "Author Name";
// Indexer
int i = 2;
// Loop to read through the database returned data
while (MySQLReader.Read())
{
// Writing the data from the database table column BookName
((Excel.Range)MyWorkSheet.Cells[i, 1]).Value2 =
MySQLReader["BookName"];
// Writing the data from the database table column Author
((Excel.Range)MyWorkSheet.Cells[i, 2]).Value2 =
MySQLReader["Author"];
i++;
}
// Dispose the SQL command
MySQLCommand.Dispose();
// Closing SQL connection after using it.
MySQLConnection.Close();
}
The following screenshot displays data retrieved from Microsoft SQL Server 2008 database and the data being displayed in the worksheet cells.
In this demonstration, you learned how to connect with a Microsoft SQL Server 2008 database in order to get data and populate it in a workbook. This is just one of the ways of manipulating data outside of a workbook.
Table of Contents
- Introduction
- Building the Sample
You can download the source code from this link Source
Code Link
Introduction
The main purpose of this article is to explain how to create simple Excel and Microsoft Word Add-Ins using Visual
Studio Tools for Office (VSTO).
VSTO is available as an add-in tool with Microsoft Visual Studio. Using Visual Studio we can develop our own custom controls for Office tools like Excel, Word and and so on.In
our demo program We have used Visual Studio 2010 and Office 2007.
Building the Sample
This article explains a few basic things to create our own Custom Add-Ins for Excel and Word as follows.
1. Excel Add-Ins
- Add text to any Excel selected active Excel cell.
- Add an image to Excel from our Custom Control.
- Load data from a database and display the search result data in Excel.
2. Word Add-Ins
- Export Word to PDF.
- Add Image to Word Document.
- Add Table to Word document.
Description
Creating Excel Add-Ins
To create our own Custom Control Add-Ins for Excel.
Step 1
Create a new project and select Office 2007 Excel Add-In as in the following Image. Select your Project Folder and enter your Project Name.
Step 2
Now we can see that the Excel ThisAddIn.Cs file has been created in our project folder and we can find two default methods in this class as in the following image. “ThisAddIn_Startup”
In this event we can display our own custom Control Add-Ins to Excel. We can see the details in the code part.
Step 3
Add a new UserControl to your project to create your own Custom Excel Control Add-In.
Right-click your project->Click Add New Item->Add User Control and Name the control as you wish. Add all your Controls and design your user control depending on your requirement.
In our example,We are performing 3 types of actions in User Controls.
- Add Text: In this button click event I will insert the text from the Text box to the Active Selected Excel Cell. Using “Globals.ThisAddIn.Application.ActiveCell”
we can get the current active Excel cell. We store the result in an Excel range and now using the range, value and color we can set our own text and colors to the active Excel Cell.
private void btnAddText_Click(object sender, EventArgs e)
{
Excel.Range objRange = Globals.ThisAddIn.Application.ActiveCell;
objRange.Interior.Color = Color.Pink; //Active Cell back Color
objRange.Borders.Color = Color.Red;// Active Cell border Color
objRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
objRange.Value = txtActiveCellText.Text; //Active Cell Text Add
objRange.Columns.AutoFit();
}
2. Add Image: using
the Open File Dialog we can select our own image that needs to be added to the Excel file. Using the Excel.Shape we can add our selected image to the Excel file.
private void btnAddImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.FileName = "*";
dlg.DefaultExt = "bmp";
dlg.ValidateNames = true;
dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Bitmap dImg = new Bitmap(dlg.FileName);
Excel.Shape IamgeAdd = Globals.ThisAddIn.Application.ActiveSheet.Shapes.AddPicture(dlg.FileName,
Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue,
20, 30, dImg.Width, dImg.Height);
}
System.Windows.Forms.Clipboard.Clear();
}
Search and bind Db Data to Excel: Now
we can create our own Custom Search control to be used in Excel to search our data from the database and bind the result to the Excel file.
Creating the table
-- Create Table ItemMaster in your SQL Server - This table will be used for search and bind result to excel.
CREATE
TABLE
[dbo].[ItemMasters](
[Item_Code] [
varchar
](20)
NOT
NULL
,
[Item_Name] [
varchar
](100)
NOT
NULL
)
-- insert sample data to Item Master table
INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])
VALUES
(
'Item001'
,
'Coke'
)
INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])
VALUES
(
'Item002'
,
'Coffee'
)
INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])
VALUES
(
'Item003'
,
'Chiken Burger'
)
INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])
VALUES
(
'Item004'
,
'Potato Fry'
)
In the button search click event we search for the data from the database and bind the result to an Excel cell using “Globals.ThisAddIn.Application.ActiveSheet.Cells”.
This will add the result to the active Excel sheet.
private
void
btnSearch_Click(object
sender, EventArgs e)
{
try
{
System.Data.DataTable dt =
new
System.Data.DataTable();
String ConnectionString =
"Data Source=YOURDATASOURCE;Initial Catalog=YOURDATABASENAME;User id = UID;password=password"
;
SqlConnection con =
new
SqlConnection(ConnectionString);
String Query =
" Select Item_Code,Item_Name FROM ItemMasters Where Item_Name LIKE '"
+ txtItemName.Text.Trim() +
"%'"
;
SqlCommand cmd =
new
SqlCommand(Query, con);
cmd.CommandType = System.Data.CommandType.Text;
System.Data.SqlClient.SqlDataAdapter sda =
new
System.Data.SqlClient.SqlDataAdapter(cmd);
sda.Fill(dt);
if
(dt.Rows.Count <= 0)
{
return
;
}
Globals.ThisAddIn.Application.ActiveSheet.Cells.ClearContents();
Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 1].Value2 =
"Item Code"
;
Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 2].Value2 =
"Item Name"
;
for
(
int
i = 0; i <= dt.Rows.Count - 1; i++)
{
Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 1].Value2 = dt.Rows[i][0].ToString();
Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 2].Value2 = dt.Rows[i][1].ToString();
}
}
catch
(Exception ex)
{
}
}
Step 4
Now we have created our own User Control to be added to our Excel Add-Ins. To add this user control to our Excel Add-In as we have already seen that the Excel Addin class “ThisAddIn.Cs” has start and stop events. Using
the Office “CustomTaskpane” we can add our user control to Excel as an Add-In as in the following.
private
Microsoft.Office.Tools.CustomTaskPane customPane;
private
void
ThisAddIn_Startup(object
sender, System.EventArgs e)
{
ShowShanuControl();
}
public
void
ShowShanuControl()
{
var txtObject =
new
ShanuExcelADDIn();
customPane =
this
.CustomTaskPanes.Add(txtObject,
"Enter Text"
);
customPane.Width = txtObject.Width;
customPane.Visible =
true
;
}
Step 5
Run your program and now we can see our user control has been added in the Excel File as an Add-In.
Next we will see how to create Add-Ins for Word Documents using a Ribbon Control.
Creating Word Add-Ins:
In my example I have used Visual Studio 2010 and Office 2007.
The following describes how to create our own Custom Control Add-Ins for Word.
Step 1
Create a new project and select Office 2007 Word AddIn as in the following Image. Select your Project Folder and enter your Project Name.
Step 2
Add a new Ribbon Control to your project to create your own Word Control Add-In.
Right-click your project then click Add New Item -> Add Ribbon Control and name the control as you wish.
Add all your controls and design your user control depending on your requirements. By default in our Ribbon Control we can see a “RibbonGroup”. We can add all our controls to the Ribbon Group. Here
in my example I have changed the Group Label Text to “SHANU Add-In”. I have added three Ribbon Button Controls to the group. We can add an image to the Ribbon Button Controls and set the properties of the Button Control Size as “RibbobControlSizeLarge”.
Here I have added three Button Controls for export the Word as a PDF, add an image to Word and add a table to the Word file.
Step 3
Export to PDF File Button Click.
Using the “Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat” we can save the Word document to the PDF file. I have used the Save file dialog to save the PDF file into our selected path.
private
void
btnPDF_Click(object
sender, RibbonControlEventArgs e)
{
SaveFileDialog dlg =
new
SaveFileDialog();
dlg.FileName =
"*"
;
dlg.DefaultExt =
"pdf"
;
dlg.ValidateNames =
true
;
if
(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat(dlg.FileName, word.WdExportFormat.wdExportFormatPDF, OpenAfterExport:
true
);
}
}
Step 4
Here we will add an image to Word. Using the Open File Dialog we can select our own image to be added to the Word file. Using the “Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture” method we can add our
selected image to the Word file.
private
void
btnImage_Click(object
sender, RibbonControlEventArgs e)
{
OpenFileDialog dlg =
new
OpenFileDialog();
dlg.FileName =
"*"
;
dlg.DefaultExt =
"bmp"
;
dlg.ValidateNames =
true
;
dlg.Filter =
"Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png"
;
if
(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture(dlg.FileName);
}
}
Step 5
Here we will add a table to Word. Using the “Globals.ThisAddIn.Application.ActiveDocument.Tables” method we can add a table to the Word file. In my example I have created a table with 4 columns and 3 rows.
private
void
button1_Click(object
sender, RibbonControlEventArgs e)
{
Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(Globals.ThisAddIn.Application.ActiveDocument.Range(0, 0), 3, 4);
.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorSeaGreen;
Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Font.Size = 12;
Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows.Borders.Enable = 1;
}
Step 6
Run your program and now you will see your own Ribbon Control has been added to the Word file as an Add-In.
You can download the source code from this link Source
Code Link
The VSTO bit I understand. Visual Studio has the project templates to get you started with creating nice .NET based add-ins.
But where is VSTA? I installed the SDK but it seems to be gears towards adding extensibility to your own applications.
I had thought that VSTA was like the new VBA for Office 2007. Infopath 2007 seems to be VSTA enabled but I cannot seem to find where Excel 2007 is also VSTA enabled.
Am I missing something ?
iDevlop
24.6k11 gold badges89 silver badges147 bronze badges
asked Nov 2, 2008 at 17:35
As I understand it, VSTA is not a ‘new VBA’ nor built into Office 2007, but a separate ‘Super-VBA with .NET’ that must be licensed from Summit, and distributed as part of an external application. I think it’s just targeted at ISVs wishing to extend Office, but the blurb about it also contains this gem:
Perhaps the feature most applauded by enterprise BDMs and SI’s is that VSTA customizations are seamlessly opened by any version of Visual Studio enabling professional developers to continue to enhance applications originally created by end user developers – a feature requested by many enterprises because applications often grow in sophistication over time.
I’ve not bothered googling BDMs and SI means le Système International d’Unités to me, but I took this mean that you can take the horrible mess of excel VBA that your traders used to turn worthless morgages into goldmine CDOs (and then bailouts), and your ‘real developers’ can open it in Visual Studio and sort the mess out (or just quit…).
also VBA and VSTA can exist together:
http://blogs.msdn.com/vsta/archive/2006/07/31/684514.aspx
answered Apr 2, 2009 at 14:35
Colin PickardColin Pickard
45.5k13 gold badges98 silver badges147 bronze badges
0
If I understand correctly, VSTA is a new technology that provides a «standard» short-cut route to extensibility for application vendors. So it may appear in Office apps in the future or it may not, but it’s not there now.
If it becomes supported by Excel, Word and the like, then the UI (Visual Studio Shell?) should be distributed as part of the package.
But I may be miles off-base…
answered Nov 3, 2008 at 9:13
Mike WoodhouseMike Woodhouse
51.5k12 gold badges88 silver badges127 bronze badges
From Wikipedia, the free encyclopedia
«VSTO» redirects here. For the Alvin Curran string quartet, see VSTO (string quartet).
Visual Studio Tools for Office (VSTO) is a set of development tools available in the form of a Visual Studio add-in (project templates) and a runtime that allows Microsoft Office 2003 and later versions of Office applications to host the .NET Framework Common Language Runtime (CLR) to expose their functionality via .NET.
This allows extensions to the Office applications to be written in CLI compliant languages as well as to use functionality and user interface constructs from Office applications in .NET applications.[1] Extensions to Office prior to Office 2003 only allowed the creation of COM add-ins using Visual Basic or Visual C++ and a «Developer» edition was also offered that enabled VBA developers to create COM Add-ins.
VSTO supersedes developer editions of Office 2000 and Office XP for Office development. The developer editions of Office have been discontinued after Office XP and VSTO is available for Office 2003 and later versions only. The VSTO runtime, although part of VSTO development tools, is also downloadable separately if required. COM addin development is still possible for Office 2000 and all later versions using the Shared Add-in template in any version of Microsoft Visual Studio.
The VSTO add-ins (project types and controls) are also developed using Visual Studio. For Visual Studio .NET 2003 and Visual Studio 2005, it was available only as a standalone edition with support for .NET languages limited to Visual Basic.NET and C#. It was also included as a part of the Visual Studio Team System 2005.
Later on, the Visual Studio Tools for Office 2005 Second Edition (VSTO 2005 SE) was released as a free add-in to Visual Studio Professional and above that includes Office 2007 and 2003 support. However, for Visual Studio Professional Edition, it installs only the application-level add-ins; it does not add the document-level customizations or other functionality (actions pane, host controls, visual document designer, etc.) available in the full version of VSTO or Team System editions.[2][3]
The current version is Visual Studio Tools for Office 2012 (VSTO 4.5) which is compatible with Office 2016, Office 2013, Office 2010, and Office 2007.
Comparison with VBA[edit]
Like VBA, code written for VSTO is executed by a separate virtual machine (the CLR) which is hosted inside the Microsoft Office applications. However, unlike VBA, where the code is stored in the document file itself, programs written with VSTO are stored in separate CLI assemblies which are associated with the documents by means of custom properties.[4]
If the properties are present, Microsoft Office hosts the CLR and loads the assembly specified in the property into a separate appdomain named after the document’s name.[5] VSTO applications are subject to the .NET Framework Code Access Security constraints, in addition to the digital signature based permission model that governs VBA macros.[6]
VSTO development is normally performed using Visual Studio as used by professional programmers. The Office application is (re)started for each debugging session. VBA is normally developed from within the Office application and requires no special tools. VBA also has a macro recorder that can generate VBA code from user actions which is useful for non-professional programmers.
Comparison with JavaScript API[edit]
Office extensions or add-ins can be developed using VSTO and JavaScript API technologies. VSTO is Microsoft .NET technology and add-ins using JavaScript API technology use JavaScript, HTML and CSS.
JavaScript API add-ins are highly portable across platforms like iOS, mobile phones, tablets and Windows. The complete licensing process and cycle is easy and maintained within add-ins. Interactive visualization is feasible in JavaScript API add-ins using Charts, ClipArt and Maps.
JavaScript API add-in development is comparatively new technology and is introduced with Office 2016. There are limited APIs and functions available and supported.
VSTO has complete access to all Office object models. It is feasible to perform all operations on the Office client. Features that requires accessing local machine file systems and other applications are feasible and easy in VSTO. C# or any other CLI programming language can be used to create new Office add-ins.
VSTO compatibility and add-in functionality[edit]
The latest version of VSTO, as of 2018, is «Office Tools for Visual Studio» and is available with all versions of Microsoft Visual Studio 2017.
VSTO 2003, 2005, 3.0 and 2010 runtimes install in side-by-side (SxS) mode. VSTO 2005 SE runtime replaces the earlier VSTO 2005 runtime. VSTO 2010 runtime installs side-by-side with VSTO 3.0, however, Office 2007 applications can also use the VSTO 2010 runtime. All older VSTO solutions will continue to run in newer versions of Office as long as the runtime against which they were developed is installed.
VSTO solutions developed against newer Office versions will not work in older Office versions as they lack the necessary Primary Interop Assemblies (PIAs) [7]
[8] Office 2010 applications will always use VSTO 2010 Runtime. Design-time support is as follows:
VSTO runtime version | Develop/Build against Office 2003 | Develop/Build against Office 2007 | Develop/Build against Office 2010 | .NET version | Available as | |||
---|---|---|---|---|---|---|---|---|
Document-level | Application-level | Document-level | Application-level | Document-level | Application-level | |||
VSTO 2003 | Word, Excel | — | — | — | — | — | .NET 1.1 | Available only as Visual Studio .NET 2003 VSTO SKU |
VSTO 2005 | Word, Excel | Outlook | — | — | — | — | .NET 2.0, 3.0 or 3.5 | Available as Visual Studio 2005 VSTO SKU and part of Visual Studio 2005 Team System editions |
VSTO 2005 SE | Requires VSTO 2005 for document-level customizations | Word, Excel, Outlook, PowerPoint, Visio | InfoPath | Word, Excel, Outlook, PowerPoint, Visio, InfoPath | — | — | .NET 2.0, 3.0 or 3.5 | Downloadable for Visual Studio 2005 Professional and above, however document-level customizations require original VSTO 2005 (Standalone SKU or Team System editions) |
VSTO 3.0 | Word, Excel (Builds against the VSTO 2005/2005 SE runtime) | Word, Excel, Outlook, PowerPoint, Visio, Project (Builds against the VSTO 2005 SE runtime) | Word, Excel, InfoPath | Word, Excel, Outlook, PowerPoint, Visio, InfoPath, Project, SharePoint 2007 Workflows | — | — | .NET 3.5 | Built into Visual Studio 2008 Professional and above |
VSTO 4.0 | — | — | Word, Excel | Word, Excel, Outlook, PowerPoint, Visio, InfoPath, Project | Word, Excel | Word, Excel, Outlook, PowerPoint, Visio, InfoPath, Project | .NET 3.5 or 4.0 | Built into all versions of Visual Studio 2017 |
Code developed with various editions of VSTO will only work with certain releases and editions of Microsoft Office 2003 and related products. Specifically, VSTO solutions developed in editions prior to VSTO 2005 SE will not work with any edition of Office 2003 other than Professional. VSTO solutions developed with VSTO 2005 SE will work with Office 2003 Standard (only application-level add-ins) and Professional. VSTO 2005 SE solutions will work with all editions of Office 2007.
See also[edit]
- Microsoft Visual Studio
- Visual Studio Tools for Applications (VSTA)
References[edit]
- ^ «Office and SharePoint Development in Visual Studio». msdn.com. Microsoft.
- ^ «Visual Studio 2005 Tools for the 2007 Office System (VSTO 2005 SE) Released to the Web». blogs.msdn.com. Microsoft. 9 November 2006.
- ^ VSTO features available by product combination
- ^ More on Word and Excel as CLR hosts
- ^ «Another CLR hosts are shipped from Microsoft». Archived from the original on 2008-01-18. Retrieved 2008-01-16.
- ^ VSTO Security Model
- ^ VSTO Loader and Runtime Components
- ^ VSTO web add-ins Vs Office 365 add-ins: Key differences to know
External links[edit]
- Visual Studio Tools for Office homepage
- VSTO 2.0 SE (VS 2005) Add-in (Office 2003 and Office 2007)
- VSTO 2.0 SE (VS 2005) Runtime for Office 2003 and Office 2007
- VSTO 3.0 (VS 2008) Runtime for Office 2007
- VSTO 4.0 (VS 2010/2012/2013) Runtime for Office 2007/2010/2013 (permalink)
- Jake Ginnivan: Adding Value to Software projects with VSTO Archived 2014-12-17 at the Wayback Machine
This post was originally published at http://solepano.blogspot.com
I’ve been doing some research on Visual Studio Tools for Office (VSTO) and Excel 2007 recently and found out that some very interesting features available in previous versions of VSTO for Excel 2003 are not available for Excel 2007. Here’s a summary of the current situation and the workarounds I figured out.
State of the Art
VSTO has basically two kinds of Excel add-ins: document-level customization an application-level add-ins.
The document-level customization lets you customize an Excel workbook and also reference the Application to add buttons to the command bar and so forth. The resulting add-in will be only available to the customized workbook. The great benefit of document-level customization is that you can add controls to the spreadsheets within Visual Studio, being these controls part of the VSTO object model. The VSTO objects are wrappers around the Interop ones and they add very interesting functionality, like events and databinding. The VSTO controls are in the Microsoft.Office.Tools.Excel namespace whereas the Interop ones are in Microsoft.Office.Interop.Excel.
Document-level customization project template
Document-level customization project
On the other and, an application-level add-in is, as its name implies, always visible for the host Application regardless of the opened workbook. The only class added by Visual Studio is the TheAddin one, no workbook or worksheet editors are provided. The VSTO controls are not available neither. All Excel objects that we can get access through TheAddin class are from the Microsoft.Office.Interop.Excel API.
Application-level add-in project template
Application-level add-in project
The problem is that, whereas document-level customization is available for Excel2003, is not yet available for Excel 2007. So, the spreadsheet editor is not available within Visual Studio and the VSTO extended controls cannot be used. The table below shows which kinds of add-in are available for each product combination (see Features available by product combination for the complete table listing all Office applications).
VSTO 2005 or Visual Studio Team System | VSTO 2005 SE installed with VSTO 2005 or Visual Studio Team System | VSTO 2005 SE installed with Visual Studio 2005 Professional Edition | |
Document-level customizations | Excel 2003 | Excel 2003 | Not available |
Application-level add-ins | Not available |
Excel 2003 Excel 2007 |
Excel 2003 Excel 2007 |
Workarounds
In order to make a document-level customization (or at least something similar) to target Excel 2007 I found out that some of the following things can be done:
1- Develop for Excel 2003 and deploy in Excel 2007
It is possible to develop a document-level customization in Visual Studio for Excel 2003 using VSTO 2005. The resulting customized document can then be opened in Excel 2007 in compatibility mode with the same functionality. The drawbacks of this approach is that Excel 2003 needs to be installed in the developer’s machine and that you won’t have Office 2007 features like custom panes and ribbon extensibility available.
2- Develop for Excel 2007 with VSTO SE and try to emulate the document-level customization.
In order to target Excel 2007, VSTO SE is needed and the only option by the moment is to create an application level add-in. For emulating the document customization you can create an Excel’s template file within Excel application, add the desired named ranges, tables, graphics, etc…and then access these controls trough the add-in’s code to make custom automation. The drawback of this approach is that the extended functionality of VSTO’s controls is not available. For example, you won’t be able to use the ListObject databinding support. In order to access the workbook controls, the Interop API must be used. Another drawback, is that the Interop API is not as well documented as the VSTO’s.
3- Develop an application-level add-in for Excel 2007 and create the VSTO’s objects from code.
Actually I’m not sure wheter this is really a choice, since I couldn’t make it work. What I tried here was to create a new instance of a VSTO worksheet to wrap an Interop worksheet. In ThisAddin class I have the following code:
using Excel = Microsoft.Office.Interop.Excel;
using Vsto = Microsoft.Office.Tools.Excel;
namespace ExcelAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
#region VSTO generated code
this.Application = (Excel.Application)Microsoft.Office.Tools.Excel.ExcelLocale1033Proxy.Wrap(typeof(Excel.Application), this.Application);
#endregion
try
{
Excel.Worksheet newSheet = (Excel.Worksheet)this.Application.ActiveWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Microsoft.Office.Tools.Excel.Worksheet extendedSheet = GetExtendedWorksheet(newSheet);
extendedSheet.Controls.AddNamedRange(extendedSheet.Range[«A1»,«C2»], «NamedRange»);
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
private Vsto.Worksheet GetExtendedWorksheet(Excel.Worksheet nativeWorksheet)
{
//Get the IHostItemProvider instance.
Microsoft.VisualStudio.Tools.Applications.Runtime.IHostItemProvider hostItemProvider = (Microsoft.VisualStudio.Tools.Applications.Runtime.IHostItemProvider)
RuntimeCallback.GetService(typeof(Microsoft.VisualStudio.Tools.Applications.Runtime.IHostItemProvider));
//Create the new worksheet and return it to calling function.
return new Vsto.Worksheet(hostItemProvider, RuntimeCallback, nativeWorksheet.CodeName,
null, nativeWorksheet.Name);
}
But, when trying to add the NamedRange to the extended worksheet this Exception is thrown:
This document might not function as expected because the following control is missing: Sheet4. Data that relies on this control will not be automatically displayed or updated, and other custom functionality will not be available. Contact your administrator or the author of this document for further assistance.
at Microsoft.Office.Tools.Excel.Worksheet.GetObjects()
at Microsoft.Office.Tools.Excel.Worksheet.GetPrimaryControl()
at Microsoft.Office.Tools.Excel.Worksheet.get_Range()
at ExcelAddIn1.ThisAddIn.ThisAddIn_Startup(Object sender, EventArgs e) in C:…ProjectsExcelAddIn1ExcelAddIn1ThisAddIn.cs:line 26
Conclusion
Although VSTO’s document-level customization is not available for Excel 2007 yet, there still are some choices for developing add-ins targeting this application version. Besides, the good news is that this lack will be supplied soon. VSTO «Orcas» will provide document-level customization for Excel 2007 within its new features. So, anyway, it’s just a matter of time…