Why can't i change an excel file sheets during a loop in matlab
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi,
I want this function which is an exemple store the first second and thrid value of ne in an excel sheet each but i also want to it to rename the excel sheets while writing but what i don't understand is when it's done only the first sheet will be renamed and it won't be renamed A but C
function excel(init)
Varlist = ['A' 'B' 'C']
ne = [1 2 3]
a = 1
path_save_csv=uigetdir;
cd(path_save_csv);
while a <= 3
xlswrite('data.xlsx',ne(a),a,'A1');
e = actxserver('Excel.Application');
ewb = e.Workbooks.Open('C:\Users\223080038\Desktop\data.xlsx');
ewb.Worksheets.Item(1).Name =[Varlist(1,a)] ;
ewb.Save ;
ewb.Close(false);
e.Quit ;
a=a+1
end
0 Commenti
Risposta accettata
dpb
il 4 Ott 2022
Because in
ewb.Worksheets.Item(1).Name =[Varlist(1,a)] ;
that's exactly what you told it to do -- rename Item(1) each time.
Use writematrix instead of the deprecated xlswrite and set the sheet name on write and you won't need any of the above gyrations and double-opening/closing the file anyway...
Something more like
function excel_init
Varlist = {'A','B','C'};
ne = 1:3;
path_save_csv=uigetdir;
for i=1:numel(ne)
writematrix(ne(i),fullfile(path_save,'data.xlsx'),'Sheet',Varlist(i),'Range','A1');
end
end
I'd probably pull the call to uigetdir from inside this function to the caller and pass the result as it's likely you'll want it elsewhere in the application.
3 Commenti
dpb
il 5 Ott 2022
Modificato: dpb
il 5 Ott 2022
That's getting to be quite a while back -- writetable wasn't introduced until R2013b so if you can't upgrade to a more recent version (and the table itself was also in R2013b and alone is worthy of serious consideration without other new features), then the venerable xlswrite is the tool for spreadsheets.
It also will let you specify the sheet, although it doesn't use name-value pairs to do so...
xlswrite(fullfile(path_save,'data.xlsx'),ne(i),Varlist{i},'A1')
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Spreadsheets in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!