Reputation: 1071
I am trying to figure out the best way to interact with an OLE Server using C# .NET
i have found some code that enables interaction with COM+ that appears to work for the OLE server but I wonder if there is a more elegant or simpler way?
I require that it be late bound.
Code (as pilfered from elsewhere on the net)
// Code start
Type excel;
object[] parameter = new object[1];
object excelObject;
try
{
//Get the excel object
excel = Type.GetTypeFromProgID("Excel.Application");
//Create instance of excel
excelObject = Activator.CreateInstance(excel);
//Set the parameter whic u want to set
parameter[0] = true;
//Set the Visible property
excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter);
Obviously in my case I am putting the name of my ole server in where Excel.Application is, but I have seen cases in EARLY binding where you can call the function directly off the object without having to go via 'InvokeMember'
Is this possible? Can I use Type to cast as object as my type?
Thanks.
Upvotes: 2
Views: 2222
Reputation: 2911
Try having a look at this from the add references. It gives you useful access to Excel. Microsoft.Office.Core Microsoft.Office.Interop.Excel
using Excel = Microsoft.Office.Interop.Excel;
...
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Excel.Application app;
Excel.Workbook workbook;
app = new Excel.ApplicationClass();
app.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
workbook = app.Workbooks.Open( openFileDialog.FileName,
0,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
return workbook;
}
Cells and worksheets etc can be accessed like this:
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Item[1];
worksheet.Cells.Item[6, 1]).Value;
Upvotes: 0
Reputation: 27105
If you are using .NET 4.0 you can use dynamic
instead of object
and invoke the members as if they were there. This will then be checked at runtime, and if the name is correct, execute it.
//Get the excel object
var excel = Type.GetTypeFromProgID("Excel.Application");
//Create instance of excel
dynamic excelObject = Activator.CreateInstance(excel);
excelObject.Visible = true;
Upvotes: 4