I am trying to convert an "old" .Net-3.5-Project to .Net-4.0. By now everything works fine, but the Excel-Interop.
What I am having problems with is the opening of an workbook. I already tried an all new project and compiled it once with .Net-3.5 and once with .Net-4.0. With the "old" Framework it works as excpected, but with 4.0 I only get null
as a result?
My code in my testapp is this:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Excel.Workbook test;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenWithInterop();
}
private void OpenWithInterop()
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(excel_WorkbookOpen);
test = excel.Workbooks.Open(@"C:/Test/test.xlsx");
excel.Quit();
}
void excel_WorkbookOpen(Excel.Workbook Wb)
{
if (test.Name.Equals(Wb.Name)) // Here there will be an null-exception with .net-4 but not with .net-3.5
{
Console.WriteLine("done it right");
}
}
}
}
The testapp contains only a WinForm-Form (from the template) and I added just one button that has the above shown behaviour.
Is there anything I am missing here? Did anything change in the way to work with Excel in 4.0?
UPDATE: To answer your questions:
- It's Office 2010 (x86) on Windows 7 Enterprise (x64)
- I just added it in "references" in Visual Studio and called it as "using" in my Main-Class. (Will update my code to show it full)
- That's now the real minimal code to show you the behaviour - strange isn't it?
UPDATE 2: I found out some "new" stuff:
- It's also happening on Windows XP (x86)
- You don't need to have the project, in which Excel.Interop is referenced, in .net4, it's enough that it is called by some .net4-project. Example:
BaseProject (.net-4) --> DataLayer (.net-3.5) references Excel.Interop --> Presentation (.net-4)
In this example the error will happen. Even when DataLayer is .net-3.5. BaseProject has to be .net-4, because it's calling Presentation which is .net-4 (and needs to be...)
UPDATE 3:
Just found out, that everything would work fine, but you run in really trouble if you are using one of these to events in .net4
excel.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(this.HandleWorkbookClosed);
excel.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(this.HandleWorkbookOpen);
Are there any aquivalent events in Excel._Application
like in Excel.ApplicationClass
?
UPDATE 4:
To answer the question of the comments (thanks Will!) I extended the example a little bit. The main-problem is in the event. Why is there this difference in .net-4 or is somewhere documented? And how to avoid it?