MATLAB Answers

Read from multiple excel files and write into single excel file

3 views (last 30 days)
Marwah Ababneh
Marwah Ababneh on 26 Apr 2021
Commented: Clayton Gotberg on 26 Apr 2021
I'm trying to read multiple excel files and write into single excel file using this code
source_dir = 'C:\Users\Marwah Ababneh\Desktop\Thesis\Matlab\1\Final\Database\features2' ;%my file source dir
source_files = dir(fullfile(source_dir, '*.xls'));
data = cell(length(source_files),13);
for i = 1:length(source_files)
data = xlsread(fullfile(source_dir, source_files(i).name));
end
xlswrite('Features.xls',data);
It reads all file but it writes on the file only the last read excel file
also i used this
data =[ ];
for i = 1:length(source_files)
data =[data; xlsread(fullfile(source_dir, source_files(i).name))];
end
xlswrite('Features.xls',data);
and this keeps getting the error 'Dimensions of arrays being concatenated are not consistent.'

Answers (1)

Clayton Gotberg
Clayton Gotberg on 26 Apr 2021
Edited: Clayton Gotberg on 26 Apr 2021
Your two solutions have errors because:
1) In the first one, you overwrite data in each loop, then ask it to save when it has finished looping. You need to either save all of the data (as you try to do in solution #2) or you need to write the new data each time you get it.
2) In the second one, the issue is probably that the number of columns in at least one of your excel files is different. That one's hard to troubleshoot without your data and the line the error appears on. To check this, try using this code block:
for i = 1:length(source_files)
test = size(xlsread(fullfile(source_dir, source_files(i).name)))
end
  1 Comment
Clayton Gotberg
Clayton Gotberg on 26 Apr 2021
Additionally, there are some compatibility concerns with xlsread and xlswrite, so you might look into using the readtable, readmatrix, writetable and writematrix functions.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!