A loop for multiple .xlsx files import with different names
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi,
I trying to import multiple .xlsx files from a specific folder on my Mac, but any answers that I have found on MATLAB Answers don't helped me. The files' name are {1501 1502 ... 1912} with this form: YYmm, but occasionally I could have few omissions and in this case, I would see the message: 'YYmm file doesn't exist'.
In any file, I have strings and numbers, what's the command more adequate to the importation?
source_dir = '~/Users/username/Documents/MATLAB/CDSUSD/Amundi1';
source_files = dir(fullfile(source_dir, '*.xls'));
for t = 1:length(source_files)
data = xlsread(fullfile(source_dir, source_files(t).name));
end
Thanks at all.
댓글 수: 3
채택된 답변
dpb
2020년 3월 8일
- Your wildcard specification dir(fullfile(source_dir, '*.xls')) will only find files ending in precisely 'xls' and your text says you have .xlsx files. Use dir(fullfile(source_dir, '*.xlsx')); instead unless it's possible to have either (bad idea, but it happens). dir(fullfile(source_dir, '*.xls*')); will handle that case if must.
- Your struct that dir() returns will contain no missing files so that would not be an issue using that solution (one of, if not the one) of my favorite ways to do so. Trying to build matching file names is rife with extra coding to do so and then processing to handle the possible of there being missing ones.
- That said, if there are other files in the subdirectory besides those you do want and there's not another easy way to write the wildcard string to only returns the one desired besides the file type extension, then building the names is about the only alternative. In which case, then program defensively knowing it is expected to have some missing files:
for yr=1901:1903 % I'm presuming the 1501, ... was typo...
f=fullfile(source_dir,string(yr)+'.xlsx');
try
data=xlsread(f);
catch
end
end
will just skip the missing.
Will note that xlsread is deprecated on PC anyways, not sure on Mac.
댓글 수: 4
dpb
2020년 3월 10일
Then use readtable instead of xlsread. As above in the loop the try...catch block will return the numeric data only; to reconstruct both numeric and text from a spreadsheet with xlsread you have to return either
[n,t]=xlsread(fname); % numeric in n, text in t
or
[~,~,r]=xlsread(fname); % all data in cell array r as cell
either takes munging on to get both data types that can operate on subsequently.
추가 답변 (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!