How can I merge 100 .xlsx files into one file?
9 次查看(过去 30 天)
显示 更早的评论
How can I merge 100 .xlsx files into one master file while keeping the headings? My goal is to do this task without having to individually call each excel file. There are a total of 18 headings; 1 per column. There are also roughly 10k samples in each .xlsx file. i.e. the goal here is to merge all 1 million samples to one excel sheet.
7 个评论
采纳的回答
Walter Roberson
2021-5-11
%the below code does NOT assume that the input is numeric.
%the code DOES assume that all files have the same datatype for
%corresponding columns
%output file should be in different place or different extension than the
%input file, unless you add extra logic to filter the file names. For
%example if there is a constant prefix you could add that into the dir()
%call
outputname = 'all_data.xlsx';
make_sure_on_order = false;
ext = '.csv'; %according to comment, but .xlsx according to Question
dinfo = dir(['*' ext]);
filenames = {dinfo.name};
%if the name prefixes are all the same then given yyyy-MM-dd format, you
%should be able to just sort the names. But there might be reasons you need
%to process the time strings and sort based on them. For example at some
%point in the future or for some other person reading this code, the time
%component order might be different
if make_sure_on_order
[~, basenames, ~] = fileparts(filenames);
timestrings = cellfun(@(S) S(end-15:end), basenames, 'uniform', 0);
dt = datetime(timestrings, 'InputFormat', 'yyyy-MM-dd HH-mm', 'format', 'yyyy-MM-dd HH:mm');
[~, idx] = sort(dt);
filenames = filenames(idx);
else
filenames = sort(filenames);
end
nfile = numel(filenames);
datacell = cell(nfiles,1);
for K = 1 : nfile
datacell{K} = readtable(filenames{K});
end
all_data = vertcat(datacell{K});
writetable(all_data, outputname);
10 个评论
Walter Roberson
2021-5-12
When you test, if the order of output looks acceptable, then you can remove the logic that deals with timestrings and sorting based on time, using just
filenames = sort(filenames);
However if you think at some point in the future that you might need to use filenames with inconsistent prefixes, then keep the logic.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!