Combine multiple tables into one table and export as an excel file

조회 수: 25 (최근 30일)
HabenG
HabenG 2021년 11월 3일
편집: HabenG 2021년 11월 4일
I need to generate an excel file from multiple tables in my workspace, catch is all the tables have different number of rows, so I want to align them as best as possible using the first column of each table and push them out to an excel file.
I also need to put out a separate excel file for each table, is there a way to loop through the tables and generate an excel file for each of them…. So basically, how can I change the file name (meaning the excel file that i want to generate) every iteration to the appropriate table name which is at very last part of the directory/path
If it’s any help, I’ve attached a few tables and a piece of my code for a reference.

채택된 답변

KSSV
KSSV 2021년 11월 3일
files = dir('*.mat') ; % you are in the folder where mat files are present
N = length(files) ;
T = cell(N,1) ;
for i = 1:N
thisfile = files(i).name ;
temp = struct2cell(load(thisfile));
T{i} = temp{1} ;
% Write each tble to excel file
[thepath,name,extn] = fileparts(thisfile) ;
outfile = [files(i).folder,filesep,name,'.xlsx'] ;
writetable(T{i},outfile);
end
  댓글 수: 2
Stephen23
Stephen23 2021년 11월 3일
temp = struct2cell(load(thisfile));
T{i} = temp{1} ;
can be simplfied to
T(i) = struct2cell(load(thisfile));
HabenG
HabenG 2021년 11월 3일
편집: HabenG 2021년 11월 3일
Thanks Fellas. I used outjoin with merge to combine the tables and i've also decided to push all the table into a single excel file in different sheets but it seems like i can only output an excel file with only one sheet. When i try to add another table into a different sheet it wipes out data i had in another sheet.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

HabenG
HabenG 2021년 11월 3일
편집: HabenG 2021년 11월 4일
Figured it out. I combined all the table and iterated through each column and made a separate sheet for each column....hopefully this will help someone
Directory = ('C:\Users\hgheb\OneDrive\Desktop\TestForlder\Logistic.xlsx'); % Change to your directory
k = numel('your table name here'.Properties.VariableNames);
for i = 1: width(k)
writetable('your table name here'(:,[1, i]),Directory,"Sheet",i,"WriteMode","inplace"); % Here i'm keeping column 1 for all sheets while iterating through all other columns.
end

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by