Home > Net >  Merge excel files into two different ones
Merge excel files into two different ones

Time:10-25

I want to run in Matlab the below code, where for ten excel files merges them vertically into one excel file. My question is how can I merge them vertically in two different files?

 path = 'G:\2019';  
    S = dir(fullfile(path, '*', 'data.xls'))
    for k = 1:numel(S)
        F = fullfile(S(k).folder,S(k).name);
        data = readtable(F);
        d = strcat(table2array((data(:,1))), {' '}, table2array((data(:,2 ))));
        out = [d data(:,3)]; % date / time / acceleration
        out = renamevars(out,'Var1','Date & Time');
        writetable(out,'file.xls',"Sheet",k)
    end

CodePudding user response:

It seems to me that you're not properly checking you folder. I used pwd for the current folder and my matlab code was running there. I also created two folders folder1 and folder2 and so on with excel.xlsx.

You need to add an if statment to get the first file and fill the initial dataN to concatenate everything.

Then you can use something similar to enter image description here

Then you need to ignore the two first folder names from the struct, that will be . and .. respectively

So the code looks something like this:

path = pwd;
S = dir(path);
isdir = [S.isdir];
n_files = 5;
for k = 3:numel(S)
    if isdir(k)
        if k < (3   n_files)
            disp(num2str(k))
            if k == 3
                F = fullfile([path '\' S(k).name '\excel.xlsx']);
                data2 = xlsread(F);
            else
                F = fullfile([path '\' S(k).name '\excel.xlsx'])
                data = xlsread(F);
                data2 = [data2;data];
            end
        else
            if k == (3   n_files)
                F = fullfile([path '\' S(k).name '\excel.xlsx']);
                data3 = xlsread(F);
            else
                F = fullfile([path '\' S(k).name '\excel.xlsx']);
                data = xlsread(F);
                data3 = [data3;data];
            end
        end

    else
        ;
    end
end

xlswrite('file3.xlsx', data2); % Create file 3
xlswrite('file4.xlsx', data3); % Create file 3

EDIT: I misread the question and didn't see you wanted the first 5. You can simply add an if statment for that then. I'm updating the code for this. You could then change n_files to fit the quantity of files you want.

  • Related