这是在 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 中使用的任何功能,例如工作表命名等。