3

我有以下单元格数组,它是 excel 文件中一些(但不是全部)选项卡名称的列表:

选择标签 =

'Screen'
'SectorAbsolute'
'SectorRelative'

如何让它根据此列表中的内容读取 Excel 工作表的每个选项卡并返回选项卡内容表?新表应与读取的选项卡同名。

我尝试过(例如创建一个名为“SectorAbsolute”的表,其中包含“SectorAbsolute”选项卡的内容):

char(chosenTabs(2))=readtable(inputFile,'Sheet',char(chosenTabs(2)))

但这会返回错误:

您不能只使用一个下标为表格下标。表下标需要行和变量下标。

4

2 回答 2

4

一种利用结构数组的方法:

chosentabs = {'Sheet1', 'Sheet3'};
ntabs = length(chosentabs);

for ii = 1:ntabs
    mytables.(chosentabs{ii}) = readtable('test.xlsx', 'Sheet', chosentabs{ii});
end

它返回mytables一个包含您的表的结构数组。您可以显式访问工作表(例如mytables.Sheet1)或利用动态字段引用(例如mytables.(somestring)

于 2015-12-09T18:06:32.787 回答
3

因此,您可以执行以下操作,但请注意,eval不建议动态命名变量和使用:

my_command_string = [chosenTabs{i},'=readtable(inputFile,''Sheet'',chosenTabs{i})'];
eval(my_command_string);

如果我在编码:

我可能只是把它写出来(除非有很多......):

tab_Screen         = readtable(inputFile,'Sheet','Screen');
tab_SectorAbsolute = readtable(inputFile,'Sheet','SectorAbsolute');

如果有吨和吨...

利用结构,excaza 在这个答案中建议的一个看起来很漂亮。其他一些方法是:

方法一:

n_chosenTabs    = length(chosenTabs);
chosenTabs_data = cell(n_chosenTabs, 1);
for i=1:n_chosenTabs
  chosenTabs_data{i} = readtable(inputFile,'Sheet',chosenTabs{i});
end

方法二:

您还可以使用containers.Map从选项卡名称转到实际表。加载地图:

tab_map = containers.Map;
for i=1:n_chosenTabs
  tab_map(chosenTabs{i}) = readtable(inputFile,'Sheet',chosenTabs{i});
end

然后你可以使用类似的东西访问单个表。

local_copy_of_sector = tab_map('Sector');

请注意,如果您更改local_copy_of_sector它不会更改存储在容器中的副本。地图;

于 2015-12-09T17:35:04.730 回答