Why can't i change an excel file sheets during a loop in matlab
2 ビュー (過去 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!