如何从我的应用程序打开当前的Excel实例?
如何在当前打开的Microsoft Excel实例中打开我的Excel工作表? 当我使用我的代码时,将打开一个新的Excel实例。
private Excel.Application xlApp; private Excel.Workbook xlWorkBook; private Excel.Worksheet xlWorkSheet; xlApp = new Excel.Application(); xlApp.Visible = true; xlWorkBook = xlApp.Workbooks.Open(textBox1.Text); xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
您可以执行下列操作来获取对正在运行的Excel实例的引用(如果有的话):
public Excel.Application TryGetExistingExcelApplication() { try { object o = Marshal.GetActiveObject("Excel.Application"); return (Excel.Application)o; } catch (COMException) { // Probably there is no existing Excel instance running, return null return null; } }
一旦你有一个正在运行的实例的引用,你可以访问它的Workbooks集合。
一个警告:如果您尝试自动化现有的Excel实例,则可能会出现“服务器繁忙”exception。 为了避免这种情况,可以实现IOleMessageFilter
error handling程序。 本文介绍如何实现自动化Visual Studio; 该技术与自动化Excel相同。