VSTO开发中VS2010和Office 2003的问题及解决方案

因为公司需要,将以前的VSTO项目升级为Net4.0环境,用VS2010开发,结果悲剧了,VS2010的VSTO不支持Office2003,Google了一番,在博客园找到这篇文章,VSTO开发中VS2010和Office 2003的问题,明确说明Office2003已经不被支持,建议升级到Office07或10。不过如果想继续兼容Office2003,文中给出了另外两种方法:使用Extensibility建立插件或者使用COM Shim Wizards辅助托管程序的开发。
本文则成功实现Extensibility建立插件的方法,供大家参考。
1 添加Extebsibility的引用
首先用VS2010新建一个Class Library的项目,Framework设置为4.0,然后添加Extensibility的引用,


现在可以去代码中引用命名空间using Extensibility了。

using System;
using Extensibility;
using System.Runtime.InteropServices;
using Office = Microsoft.Office.Core; 

 2 设置Guid和ProgId

如下所示设置好Guid和ProgId,这个有点类似Com接口。
[GuidAttribute("2752EB47-5BC9-4F67-853C-E7A9E35B0FF9"), ProgId("ATSExcelAddIn.Connect")]
public class Connect : Object, Extensibility.IDTExtensibility2

Guid可以用VS的Guid工具辅助生成;ProgId就是程序名+类名称。

 

3 实现IDTExtensibility2接口
让你的Class继承自Object,因为Object是Net所有Type的基类,然后实现IDTExtensibility2接口,主要有以下几个函数:
public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
public void OnAddInsUpdate(ref System.Array custom)
public void OnStartupComplete(ref System.Array custom)
public void OnBeginShutdown(ref System.Array custom)
我们的代码主要放在OnConnection函数中,如:
public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
            applicationObject = application;
            addInInstance = addInInst;

            this.appExcel = (Excel.Application)application;
            System.Diagnostics.Debug.WriteLine("ATSAddIn.OnConnection: App is {0}"this.appExcel.ActiveWorkbook.FullName);
            menuBar = this.appExcel.CommandBars.ActiveMenuBar;
            menuATS32 =
                (Office.CommandBarPopup)menuBar.Controls.Add(Type: Office.MsoControlType.msoControlPopup, Temporary: true);
            menuATS32.Caption = "&Mytest";

4 添加安装项目

因为这是一个Dll项目,不能像VSTO项目那样直接F5加载到Excel中调试,我们需要添加一个Setup项目,然后使用Install来注册到Excel的插件中。

 

 

5 安装,预览效果 

打开Excel2003,现在已经可以在菜单上看见我们的程序了。 

 

分享完毕,感谢大家的阅读。 

posted on 2012-02-10 16:41  咖啡色  阅读(1995)  评论(0编辑  收藏  举报