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

22 ビュー (過去 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 件)

カテゴリ

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

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by