Why can't i change an excel file sheets during a loop in matlab
조회 수: 1 (최근 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
댓글 수: 0
채택된 답변
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
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!