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!