xls将许多单元格数组作为单独的命名工作表写入Excel



我有很多单元格数组,例如

set1 = {'year' 'date' 'day'     'time'; 
'2017' '0803' 'Monday'  '15.15'; 
'2015' '0303' 'Tuesday' '08.20'} 
set2 = {'year' 'date' 'day'    'time'; 
'2016' '0705' 'Friday' '17.15'; 
'2013' '0310' 'Monday' '18.20'}
title = {'dataset1' 'dataset2'}

我拥有的单元格数组要长得多(400-1000 行(,我有大约 20 个不同的集合,但数量会根据我的 GUI 数据而变化。我想做的是自动将所有这些数组导出到一个 Excel 电子表格中,每个数组都设置为一个单独的工作表,并在"title"字符串中指定工作表名称。

到目前为止,我正在使用

[FileNameBodeWrite, PathNameBodeWrite] = uiputfile({'*.xls'},'Save As...', ...
[Title{1,1} '.xls']);
xlswrite([PathNameBodeWrite FileNameBodeWrite ],[Set1],1,'A1') 

但这当然只适用于一个特定的集合。我想将它们全部包含在一个电子表格中,可能通过使用循环,但我不确定如何实现它?

您可以创建集合的单元格数组

sets = {set1, set2} % and so on

然后简单地循环浏览集合。使用xlswrite看起来像这样

[FileNameBodeWrite,PathNameBodeWrite] = uiputfile({'*.xls'},'Save As', [Title{1,1} '.xls']);
for ii = 1:numel(sets)
% If the sheet title{ii} doesn't exist, it will be created
xlswrite([PathNameBodeWrite FileNameBodeWrite],sets{ii},title{ii},'A1');
end

编辑

分配sets = {set1, set2}等是复制内存中的所有数据。引用集合的更有效方法是使用匿名函数句柄。本质上,我们指向单元数组,而不是将副本存储在另一个单元数组中:

% Using the @ notation to define anonymous functions
sets = {@()set1, @()set2};
for ii = 1:numel(sets)
% Note the brackets after sets{ii}(), this calls the function handle in sets{ii}
xlswrite([PathNameBodeWrite FileNameBodeWrite],sets{ii}(),title{ii},'A1');
end

即使是这个小例子也能看到差异

sets = {set1, set2}; whos sets
>> Name   Size   Bytes  
sets   1x2    3126   
sets = {@()set1, @()set2}; whos sets
>> Name   Size   Bytes  
sets   1x2    288 

请注意,尽管上述方法应该有效,但它会很慢,因为每次使用xlswrite时您都会打开和关闭文件。更快的方法是直接访问 Excel 对象。由于您是新手,我可能会坚持使用有效的方法,但是如果您想优化内容,那么文件交换功能xlswrite1使其相对容易。

最新更新