More C# Automating to Excel

泪湿孤枕 提交于 2019-12-21 06:01:19

问题


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(...)


来源:https://stackoverflow.com/questions/4789476/more-c-sharp-automating-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!