More C# Automating to Excel

2020-06-27 10:48发布

问题:

This launches a fresh Excel workbook:

        Excel.Application oXL;
        Excel._Workbook oWB;

        oXL = new Excel.Application();
        oXL.Visible = true;

        oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));

However, what if one wants to either...

-- 'GetObject' (in the familiar Automation paradigm) to a workbook that's already loaded and open on the screen?, or

-- access and write data to a closed workbook by path name?

Both of which are doable by old standards. Preferably the latter although I'm not a chooser right now. Thanks for any help.

回答1:

You can get an existing instance of Excel using:

Marshal.GetActiveObject("Excel.Application")

This will throw a COMException if there is no instance of Excel running.

One pitfall of automating an instance of Excel that is visible is that your calls may fail because Excel is busy. You may need to implement IMessageFilter to avoid this problem.

As for accessing a closed workbook by path - you need to open the workbook:

oXL.Workbooks.Open(...)