Combining multiple csv files in to one

19 ビュー (過去 30 日間)
Siddhant Jaitpal
Siddhant Jaitpal 2020 年 12 月 2 日
回答済み: Mathieu NOE 2020 年 12 月 3 日
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

回答 (1 件)

Mathieu NOE
Mathieu NOE 2020 年 12 月 3 日
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

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

製品


リリース

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by