matlab - 杀死在 Matlab 中创建的 Excel 进程

标签 matlab

考虑到我要写入工作簿,我目前会终止所有 Excel 进程,以便我的代码在循环调用时正常工作。

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

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

最佳答案

这是 R2015b 前后某处引入的一项“功能”,用于加速对 Excel 的多次写入……对用户/内存不是很友好!

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

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

一个厚颜无耻的选择是复制xlswrite,添加它创建的Excel变量作为输出,然后退出删除 之后,如下所示。我不主张破坏 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 中使用的任何功能,例如工作表命名等。

关于matlab - 杀死在 Matlab 中创建的 Excel 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144339/

相关文章:

matlab - 通过单击子图显示整个图像

matlab - 制作静态图例,独立于实际剧情

Matlab:查找矩阵每一列首次出现的行索引(不使用循环)

matlab - 从 SerialForwarder 的套接字读取数据

Matlab类方法错误

image - 将 Microsoft Paint 与 Matlab 代码结合使用

r - 在 R 中实现 Matlab fspecial 函数

导数符号符号的Matlab变化

matlab - 如何从图中获取点之间的值?

matlab - 如何从 MATLAB 更改 HDF5 文件中的数据类型?