更多的C#自动化到Excel更多、Excel

2023-09-03 05:21:51 作者:天涯浪人

这将启动一个新的Excel工作簿:

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的(在熟悉自动化模式),以这已经加载并在屏幕上打开的工作簿?或

-- '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?

这两者都是可行的由旧标准。 preferably后者虽然我不是一个选择器现在。感谢您的帮助。

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

推荐答案

您可以用得到的Excel现有实例:

You can get an existing instance of Excel using:

Marshal.GetActiveObject("Excel.Application")

这将抛出一个收到COMException如果有Excel的运行没有实例。

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

自动化Excel的实例,它是可见的一个缺陷是,您的通话可能会失败,因为Excel是忙。您可能需要实现 IMessageFilter 避免此问题

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