VS2005的Excel操作(一) - 添加Excel命名空间的支持

在VS2005中对Excel进行编程,首先要在对象引用中添加Microsoft Excel Object Libray,对于Office2003,应该是Microsoft Excel 11 Object Libray,Office2007则是Microsoft Excel 12 Object Libray.

 

添加引用的方法可以参见文章

《使用COM组件实现对Excel文件的操控

 

按照上述文章,我第一次添加Excel对象库的时候,引用中也出现了Excel,但是程序一直编译不过,后来再查资料,在MSDN的一篇文章发现了问题所在:

 

When you select the referenced IA in Solution Explorer, if the Copy Local property in the Properties pane is set to True, you are referencing an autogenerated IA, not the PIA. You should remove this reference and add the correct one. If you correctly reference the Excel 2003 PIA, your Excel reference's Copy Local property will be False and the Path property, on a Windows XP machine, should look something like this:


C:/WINDOWS/assembly/GAC/Microsoft.Office.Interop.Excel/11.0.0.0__71e9bce111e9429c/Microsoft.Office.Interop.Excel.dll

 

PS:

IA - Interop Assembly

PIA - Primary Interop Assembly

GAC - Global Assembly Cache

 

我的工程文件中的Copy Local属性值为True, Path属性的职位工程文件所在的目录,不是上面中提到的GAC目录。

 

MSDN的文章中还提到了解决方法:

 

Note that if you are doing development work, you shouldn't do a Typical install of Office 2003 if you want the PIAs. Because of a known bug in Visual Studio .NET and Visual Studio 2003, if PIAs are set to install on demand, as they are in a Typical install, when you reference an Office COM type library you might end up getting a Visual Studio–generated IA. To avoid this issue, do a Complete or Custom install to make sure the Office 2003 PIAs that you need to reference are already installed in the GAC before you start any development work.

 

Also note that PIA registrations get clobbered a lot. Sometimes a simple action such as installing some arbitrary independent software can clobber a PIA registration. If you know you have the Office 2003 PIAs in the GAC but somehow you keep getting an IA and not the PIA, some type library registration might have broken that specific PIA registration. To fix this, you can do any of the following:

  • Do an Office repair: Control Panel || Add/Remove Programs || Office || Change | Repair.
  • Reinstall the affected PIA. To do this, rerun Office setup.
  • RegAsm that PIA from the GAC to reregister that PIA. For example, to RegAsm the Office PIA (substituting, say, C:/windows or C:/winnt for %systemroot%):
    %systemroot%/Microsoft.NET/Framework/v1.1.4322/RegAsm.exe 
    %systemroot%/assembly/GAC/Office/11.0.0.0__71e9bce111e9429c/Office.dll
  • Finally, note that when you deploy a solution that uses the Office 2003 PIAs, you should not deploy the PIAs themselves. Office setup should be the only mechanism for installing the Office 2003 PIAs.

我先是修复Office2003不好使,只好重新安装,在下面的Office2003安装的这个界面中要注意选中.NET Programmability Support。这样在添加引用时才能正确引用Excel对象。

 

VS2005的Excel操作(一) - 添加Excel命名空间的支持_第1张图片

 

Office2003中的每个组件都要安装.NET Programmability Support,所以在Excel选项中也要选中这项。

 

再次编译程序,通过。

你可能感兴趣的:(VS2005的Excel操作(一) - 添加Excel命名空间的支持)