通过Interop启动无GUI Excel时,ExcelAsyncUtil.QueueAsMacro报空引用异常如何解决?
问题描述
我正尝试为Excel中后台工作线程运行的函数编写单元测试。正常用户流程中,后台工作线程完成后使用ExcelDNA的ExcelAsyncUtil.QueueAsMacro处理结果可正常运行:
private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // 这是工作线程完成后的代码 ExcelAsyncUtil.QueueAsMacro(() => { string[] outputs = (string[])e.Result; if (outputs.Length < 1) { MessageBox.Show("Unable to retrieve result", title, MessageBoxButtons.OK, MessageBoxIcon.Warning); Common.ExitToExcel(); return; }
但在单元测试中,Excel窗口不可见时运行该逻辑会触发以下错误:
ExcelDna.Integration.dll!ExcelDna.Integration.ExcelAsyncUtil.QueueAsMacro(ExcelDna.Integration.ExcelAction action) 未知
引发异常:'System.NullReferenceException'类型的未处理异常在ExcelDna.Integration.dll中发生,对象引用未设置到对象的实例。
测试模式下Excel通过Excel Interop启动:
xl.Application excelApp = new xl.Application(); //open an Excel application with the given workbook xl.Workbook workbook = excelApp.Workbooks.Open(filepath);
请问通过Interop启动无GUI的Excel时,需如何正确初始化ExcelDNA Integration?
解决方案
手动加载ExcelDNA加载项:无GUI模式下Excel不会自动加载默认加载项,需通过Interop手动指定加载项路径并安装:
string addInPath = @"C:\Path\To\Your\AddIn.xll"; excelApp.AddIns.Add(addInPath).Installed = true;初始化ExcelDNA集成环境:加载加载项后,调用ExcelDNA的初始化方法,确保其内部依赖的Excel上下文正确建立:
ExcelDna.Integration.ExcelIntegration.Initialize();测试环境替换
QueueAsMacro逻辑:由于无GUI模式下Excel消息循环存在限制,可通过条件编译在测试时直接同步执行委托逻辑,绕开异步队列依赖:#if TEST string[] outputs = (string[])e.Result; if (outputs.Length < 1) { Assert.Fail("Unable to retrieve result"); return; } // 后续测试逻辑 #else ExcelAsyncUtil.QueueAsMacro(() => { string[] outputs = (string[])e.Result; if (outputs.Length < 1) { MessageBox.Show("Unable to retrieve result", title, MessageBoxButtons.OK, MessageBoxIcon.Warning); Common.ExitToExcel(); return; } // 生产环境逻辑 }); #endif临时开启可见性调试:若需排查问题,可临时设置Excel可见,确保消息循环正常运行(仅用于调试,不适合正式无GUI测试):
excelApp.Visible = true;
内容的提问来源于stack exchange,提问作者OJones

