Saving tables as separate Excel file with different file names
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi all. I'm relatively new here. Just like to ask if there is a way to save tables into different Excel files with different file names?
By running this code in the uploaded 'sample.mat' file:
for hh = [1:4]
Group = table2array(sample);
Group_idx = Group(:,5) == hh;
Final_Group(hh).iter = array2table(Group(Group_idx,:));
Final_Group(hh).iter.Properties.VariableNames = {'Customer','x','y','d','X_cluster'}
end
I would be able to separate the initial 50x5 table into a struct containing 4 different sized tables grouped according to the Column 5, 'X_cluster'. (See uploaded 'Final_Group.mat')
My questions are the following:
1.) Is there a way to save the 4 different tables within the Final_Group struct into 4 separate Excel files having different file names? (e.g. Final_Group(1).iter will be saved as Results1.xlsx, Final_Group(2).iter will be saved as Results2.xlsx, etc...)
2.) If #1 is possible, can those Results1.xlsx, Results2.xlsx, etc... files be loaded back into Matlab automically? (i.e. NOT loaded one-by-one manually using their unique file name)
Any help is greatly appreciated.
Thank you.
댓글 수: 0
답변 (1개)
Mathieu NOE
2020년 11월 29일
hello ,
this is a code that will do the job and also vice versa
but IMHO, it's better so save your different data in one excel file with multiple sheets rather than multiple excel files
of course you are free to modify the code
load('sample.mat');
Group = table2array(sample);
VariableNames = {'Customer','x','y','d','X_cluster'};
filename_out = 'test.xlsx';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% part 1 : Saving Data to excel - multiple sheets
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for hh = [1:4]
Group_idx = find(Group(:,5) == hh);
Final_Group{hh} = Group(Group_idx,:);
% export to excel
writecell(VariableNames,filename_out,"Sheet" ,hh,"Range",'A1'); % save column headers in first line
writematrix(Final_Group{hh},filename_out,"Sheet" ,hh,"Range",'A2'); % save data (cell) to excel file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% part 2 : Importing Data from excel across multiple sheets and filenames.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[~,sheet_name]=xlsfinfo(filename_out);
for k=1:numel(sheet_name)
[~,~,newdata{k}]=xlsread(filename_out,sheet_name{k});
end
% Now all your data are in the variable data.
댓글 수: 5
Mathieu NOE
2020년 11월 30일
hi
I understand the input data are the same , but the final code is different , or ?
that's what I am interested to see
참고 항목
카테고리
Help Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!