Trouble reading 6 excel files (with multiple sheets) and storing each excel as a its own matrix with my loop.

1 回表示 (過去 30 日間)
JM
JM 2018 年 3 月 29 日
コメント済み: JM 2018 年 3 月 29 日
Here is my current code
%My Code
foldername = 'My Folder Path';
files = dir(fullfile(foldername, '*.xlsx'))
for i = 1:length(files)
data = xlsread(fullfile(foldername,files(i).name));
end
This code works in some respect, however data only seems to hold 1 sheet from 1 excel file, despite the files variable having all 6 files in a 6x1 struct.
Ideally what I would like is 6 separate variables (or one that stores all six files, where I can reference specific files) in my workspace.
Then, I want to be able to reference data{sheets{columns/rows across every sheet}}. I believe I can do this part, its more so getting past the hurdle of importing each excel file.
Hope that makes sense and someone can offer some advice. Thank you.
  1 件のコメント
Elias Gule
Elias Gule 2018 年 3 月 29 日
you are overwriting the values stored in the variable "data" in that for loop. So the data stored in the variable will be from the last file that was processed.

サインインしてコメントする。

回答 (2 件)

Elias Gule
Elias Gule 2018 年 3 月 29 日
Doing this might help: Replacing
data = xlsread(fullfile(foldername,files(i).name));
with
data{i} = xlsread(fullfile(foldername,files(i).name));
where data{i} contains data from the ith file.
  1 件のコメント
JM
JM 2018 年 3 月 29 日
Hi Elias, Thank you for the quick response.
I made the change you suggested and it seems to be taking the code in the right direction, however now I am getting 1x6 cell in data that contains the first sheet of each of the 6 excel files instead of containing all 30 sheets for each excel. Any idea why this might be?
Thank you.

サインインしてコメントする。


Elias Gule
Elias Gule 2018 年 3 月 29 日
ok, lets do this then:
foldername = 'My Folder Path';
files = dir(fullfile(foldername, '*.xlsx'))
for i = 1:length(files)
xldata = xlsread(fullfile(foldername,files(i).name));
data{i} = xldata;
end
  1 件のコメント
JM
JM 2018 年 3 月 29 日
Hey Elias,
With this code I am getting a 1x6 cell that has 6 sheets again and xldata has a 3006x20 double which is the contents of 1 sheet.
For some reason it still wants to only take the first sheet of each file in the data variable.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Import from MATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by