Why can't i change an excel file sheets during a loop in matlab

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

采纳的回答

dpb
dpb 2022-10-4
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 个评论
dpb
dpb 2022-10-5
编辑:dpb 2022-10-5
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')

请先登录,再进行评论。

更多回答(0 个)

标签

产品


版本

R2012a

Community Treasure Hunt

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

Start Hunting!

Translated by