Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an specific version of Excel in a C# program

For many reasons, I have installed on my laptop MSExcel 2003 and MSExcel 2007. I need both versions to develop specific projects for each version (Document level projects and Application level projects). Now I need to do a WinForm project that opens an Excel file, read a CustomXMLParts and write a new Excel file. I'm using a reference to Microsoft.Office.Interop.Excel that use ..\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Excel.dll library (it's for Excel 2007). And for this code:

Microsoft.Office.Interop.Excel.Application excelApplication;    
excelApplication = new Microsoft.Office.Interop.Excel.ApplicationClass();
string version = excelApplication.Version;

At this point version is "11.0", but I need to open Excel 2007 and it must be "12.0", and then when the program try to get the CustomXMLParts, throws an Exception because this method doesn't exist in 2003.

If I uninstall Excell 2003 it works fine, but I need to work with both (2003 and 2007). When I reinstall Excell 2003, it fails again. I check the property "Specific Version", for the Interop.Excel reference, to be sure that it's true, and I tried to modify the app.config oldVersion="12.0.0.0" to not make compatible with Excel 2003, but nothing happens:

  <assemblyIdentity name="Microsoft.Office.Interop.Excel"  publicKeyToken="71E9BCE111E9429C" culture="neutral"/>
  <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="12.0.0.0"/>

Any idea?

I'm using Visual Studio 2008 and Visual Studio Tools for Office.Thanks in advance.

like image 979
Oriol Terradas Avatar asked Nov 06 '22 19:11

Oriol Terradas


2 Answers

Probably not the answer you are looking for, but have a look at this SO question: Trying to do Office Automation with Excel 2007, but keeps using Excel 2003

like image 191
Tim Lentine Avatar answered Nov 14 '22 22:11

Tim Lentine


You could use ExcelPackage on Codeplex for your xlsx documents. Then there is no need or using interop. They have example code for reading and writing xlsx files.

This way you can continue to use interop for 2003 without them interfering.

If you need to use interop with both version you should load the assemblies using each version in a separate AppDomain in order to get them separated.

like image 32
Mikael Svenson Avatar answered Nov 14 '22 23:11

Mikael Svenson