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

6 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2018-8-14
编辑:Stephen23 2018-8-14
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 个评论
Stephen23
Stephen23 2018-8-15
编辑:Stephen23 2018-8-15
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 2018-8-15
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.

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by