Looping through Excel files in a folder.

65 views (last 30 days)
Lillian Lau
Lillian Lau on 11 Jul 2018
Commented: Ahisa on 30 Jun 2021
Hello! I have a folder is 200 Excel files with data that I need to process. How do I loop through all the files (they all have names like node-1-2, node-1-3, etc.) and perform the necessary calculations? Thanks in advance.

Answers (2)

Michiele Ogbagabir
Michiele Ogbagabir on 11 Jul 2018
You can use the dir function to get a list of all the files you want.
files = dir('path-to-your-folder/*.xlsx');
for file = files
load(file.name)
end

Hermes Suen
Hermes Suen on 11 Jul 2018
Hi, the answer will depend on what type of data you have, and what you want to do with the data but in general you can use xlsread MATLAB function and build the file name in a for loop.
for i=1:numExcelFiles
baseFileName = 'node-1';
extension = num2str(i); %Converts number into a string type
filename = strcat(baseFileName, extension, 'xlsx'); %Assuming all of your files are of the
% format node-1-someNumber.xlsx, this
%combines everything into one string
data(i) = xlsread(filename) %This will read in all the data from the filename and store it into
%data(i). However you can look at the documentation for this function to
%read in specific ranges, sheets, or tabs of data from the excel file
%%Process the data here
end
This code can also be modified if your filenames change by using if statements, or other mechanisms in the for loop. Let me know if you have any further questions
  1 Comment
Ahisa
Ahisa on 30 Jun 2021
how would one mofidy this to pull data from files that have different names but have one word in common? so, for example:
HATS12_343
HATS12_345
HATS23_343
and so on, I only want to grab the HATS12

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!