【问题标题】:Kill Excel process created in Matlab杀死在 Matlab 中创建的 Excel 进程
【发布时间】:2019-05-15 08:03:49
【问题描述】:

鉴于我写入工作簿,我目前终止所有 Excel 进程,以便我的代码在我循环调用它时工作。

xlswrite(path,values);
system('taskkill /F /IM EXCEL.EXE');

这使我在处理另一个 Excel 文件时无法运行代码。如何使 Matlab 仅终止自身创建的 Excel 进程?

【问题讨论】:

  • 自 R2019a 起,writematrix 或 writecell 是用于写入 excel 文件的推荐函数。
  • @rahnema1 这些不是有同样的问题吗?我已经使用类似名称的writetable 很长时间了,如果写入 xlsx,它相信它会打开一个隐藏的 Excel 实例...
  • @Wolfie 这些函数有一个选项“UseExcel”,应该设置为false。

标签: matlab


【解决方案1】:

这是在 R2015b 左右引入的一项“功能”,用于加快对 Excel 的多次写入……对用户/内存不太友好!

xlswrite 文档链接到此MathWorks Support Answer 以使用actxserver 手动写入 Excel,然后您可以手动删除引用 Excel 的 COM 对象。

您实际上可以edit xlswrite 并看到它使用matlab.io.internal.getExcelInstance,它做同样的事情并使用actxserver 创建一个COM 接口。

一个厚颜无耻的选择是复制xlswrite,添加它创建的Excel 变量作为输出,然后添加Quit 和delete,如下所示。我不主张破坏 The MathWorks 对该函数的任何版权所有权。

一个不那么厚颜无耻的选择是根据我上面链接的答案创建一个类似的函数,仅用于写入数据,它看起来像这样:

function xlswriteClean( File, Data, Range )
% XLSWRITECELAN writes data like XLSWRITE, but deletes the Excel instance! 
%  XLSWRITECELAN (FILE,DATA,RANGE) writes the variable in
%  DATA to FILE, in the range specified by RANGE. 
%  RANGE is optional, defaults to "A1"
    % Obtain the full path name of the file
    % Could handle this more elegantly, i.e. 
    % this always assumes the current directory, but user might give a full path
    file = fullfile(pwd, File);
    % Open an ActiveX connection to Excel
    h = actxserver('excel.application');
    %Create a new work book (excel file)
    wb = h.WorkBooks.Add();
    % Select the appropriate range
    if nargin < 3
        Range = 'A1';
    end
    rng = h.Activesheet.get('Range', Range); 
    % Write the data to the range
    rng.value = Data; 
    % Save the file with the given file name, close Excel
    wb.SaveAs( File );  
    % Clean up - the point of this function
    wb.Close;
    h.Quit;
    h.delete;
end

您基本上可以使用 COM 对象 h 自定义新 Excel 工作簿中的所有内容,因此您可以添加您在 xlswrite 中使用的任何功能,例如工作表命名等。

【讨论】:

    【解决方案2】:

    你可以通过powershellstartexcel进程获取进程id,然后使用进程id杀掉进程:

    [~, pid] = system('powershell (Start-Process excel.exe -passthru).Id');
    % Do your work
    % ...
    system(['powershell Stop-Process -Id ' pid])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      相关资源
      最近更新 更多