Azzera filtri
Azzera filtri

How to combine 3 (or more) separate CSV files into one Excel file with multiple sheets

8 visualizzazioni (ultimi 30 giorni)
Hi everyone,
I have a problem. I have three separate CSV files, all with different headers, that I want to combine into one Excel file with multiple sheets, so that each sheet, of course, represents each CSV file.
I may need to combine more than three later on, but for now, three will do. I do not have any code for this because I honestly have no idea how to start. I know how to read in the files themselves, but combining them eludes me. To create the CSV files, I am using 'csvwrite_with_headers', a file I dopwnloaded a while ago from Matlab Central. The file names are 'Pressdata5050.csv', 'Tempdata5050.csv', and 'Velocitydata5050.csv'.
I would appreciate any help you could provide.
p.s. I'm using R2018a

Risposta accettata

Stephen23
Stephen23 il 14 Ago 2018
Modificato: Stephen23 il 14 Ago 2018
D = 'path of folder where the CSV files are';
S = dir(fullfile(D,'*.CSV'));
for k = 1:numel(S)
mat = csvread(fullfile(D,S(k).name)); % or whatever loads your data
xlswrite('merged.xlsx', mat, fileparts(S(k).name))
end
If the CSV files contain text then use xlsread instead of csvread:
[~,~,mat] = xlsread(fullfile(D,S(k).name));
  5 Commenti
Stephen23
Stephen23 il 15 Ago 2018
Modificato: Stephen23 il 15 Ago 2018
Ah, my mistake, you will need to use the second output of fileparts:
D = 'C:\Users\PWayne\Documents\MATLAB';
S = dir(fullfile(D,'*.CSV'));
for k = 1:numel(S)
[~,~,mat] = xlsread(fullfile(D,S(k).name));
[~,fnm] = fileparts(S(k).name);
xlswrite('Results5050.xlsx', mat, fnm);
end
PATRICK WAYNE
PATRICK WAYNE il 15 Ago 2018
That makes me so very happy! I was opening the activex server to change the sheet names and I did not like it; still don't. Mainly because even though I closed the activex server and deleted the entry, the Excel process remained, making my workbook 'read-only' unless I either ctrl-alt-deleted and killed the process, or I deleted the workbook and compiled again................very annoying. Thank you again for all your help.

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by