opening multiple excel files in different location with a loop

1 view (last 30 days)
I am trying to write a script to take in multiple xlsx files and concatenate them.
It will have to take in different number of xlsx files depending on the situation. For example, if I input 3 location, there will be 3 xlsx file to read.
The files generally have the same name, just that they are in separate folders and are numbered. For example, if there are 5 locations, they will be numbered from 1 to 5.
% Input number of sites
N = input('Number of Location? ', 's')
% n = str2double(N)
% Loop to read all files
for i = 1:N
i = readtable(append('C:\Users\tathuen\Desktop\Data\Sample\Location', i, '\Results\Variable ', i, '.xlsx'), 'PreserveVariableNames', true)
end
I am unsure if I am heading in the right direction to write this script.
But I am stuck here as I will either get the error that 'Input must be text.' or 'For colon operator with char operands, first and last operands must be char'. What should I do?
Thanks for the help in advance :)

Accepted Answer

Wan Ji
Wan Ji on 26 Aug 2021
Edited: Wan Ji on 26 Aug 2021
Try following code
% Input number of sites
N = input('Number of Location? ', 's');
N = str2double(N)
% Loop to read all files
T = table;
for i = 1:N
Ti = readtable(['C:\Users\tathuen\Desktop\Data\Sample\Location', num2str(i),...
'\Results\Variable ', num2str(i), '.xlsx'], 'PreserveVariableNames', true);
T = [T;Ti];
end
  5 Comments
Wan Ji
Wan Ji on 26 Aug 2021
Edited: Wan Ji on 26 Aug 2021
Hi Tat Onm Huen,
Is the Number of Location an array or just a single number?
If it is an array then
% Input number of sites
N = input('Number of Location? ', 's');
N = str2num(N)
% Loop to read all files
T = table;
for k = 1:numel(N)
i = N(k);
Ti = readtable(['C:\Users\tathuen\Desktop\Data\Sample\Location', num2str(i),...
'\Results\Variable ', num2str(i), '.xlsx'], 'PreserveVariableNames', true);
T = [T;Ti];
end
Tat Onn Huen
Tat Onn Huen on 26 Aug 2021
Edited: Tat Onn Huen on 26 Aug 2021
Yes, it is an array. Thanks for your help! It works now :) @Wan Ji

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!