Combining multiple csv files in to one
23 views (last 30 days)
Show older comments
Hello ,
I have files titled in a particular order File1.csv , File2.csv .... and so on. The files contain two colums of data. I would like to combine the second column of each of the csv files into one excel file. I tried the following code snippet but resulted in output variables like filenames being blank
fileDir = 'D:\excel_folder';
outfile = 'D:\MASTER.xls';
addpath(fileDir);
fileNames = dir(fileDir);
fileNames = {fileNames.name};
fileNames = fileNames(cellfun(...
@(f)~isempty(strfind(f,'.csv')),fileNames));
for f = 1:numel(fileNames),
[~, ~, raw] = xlsread( fullfile(fileDir, fileNames{f}));
xlswrite(outfile, raw, fileNames{f});
end
Any help is appreciated
0 Comments
Answers (1)
Mathieu NOE
on 3 Dec 2020
hello
this is an alternative that worked on my pc. There may be better coding options, I admit I had a bit of a hard time figuring out why writecell did not give the expected result with an array of cells of different size. Maybe someone else will bring this later on
but so dar so good :
and also I add natsortfiles to make sure the input files are sorted according to the natural order (from the numerical values in the filename)
fileDir = cd;
outfile = 'MASTER.xlsx';
fileNames = dir(fullfile(cd,'*.csv')); % get list of files in directory
fileNames_sorted = natsortfiles({fileNames.name}); % sort file names into order
M= length (fileNames_sorted);
for f = 1:M
raw = csvread( fullfile(fileDir, fileNames_sorted{f}));
out{f} = raw(:,2);
end
% padd NaNs for shorter arrays - do we have another solution ?
maxSize = max(cellfun(@numel,out)); %# Get the maximum vector size
fcn = @(x) [x ; nan(maxSize-numel(x),1)]; %# semicolon here
rmat = cellfun(fcn,out,'UniformOutput',false); %# Pad each cell with NaNs
% writecell(rmat,fullfile(cd,outfile)); % why this does not work ??
writematrix(cell2mat(rmat),fullfile(cd,outfile)); % work around
0 Comments
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!