Changing file path and load multiple excel files

2 次查看(过去 30 天)
I have some specific folders where i have saved several excel files with the filename in the following format:
code_parameterA_year.xls, code_parameterB_year.xls, etc
where code and year changes and I need to load each excel file. I need help loading each excel file using the following code:
path = pwd
code='station1';
year='2022';
S = readtable(fullfile(path, code '_parameterA_' year'.xls'));

采纳的回答

Image Analyst
Image Analyst 2023-2-26
Use a file data store fileDatastore
% Specify the top level folder.
topLevelFolder = pwd; % Wherever it is....
% Process a sequence of files.
filePattern = fullfile(topLevelFolder, '*.xls*');
fds = fileDatastore(filePattern, 'ReadFcn',@readtable) % Create an image Datastore
% Get all filenames into one cell array. Filenames have the complete path (folder prepended).
allFileNames = fds.Files;
numFiles = numel(fds.Files);
for k = 1 : numel(allFileNames)
% Get this file name.
fullFileName = allFileNames{k};
fprintf('Processing %s\n', fullFileName);
% Now do something with fullFileName, such as passing it to readtable().
end
  4 个评论
Ancalagon8
Ancalagon8 2023-3-1
编辑:Ancalagon8 2023-3-1
using the above code from the FAQ link, I succesfully loaded all excel files:
filePattern = fullfile(myFolder, '*.xls');
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
data=readtable(fullFileName)
end
but data table only stores the last excel. Do you now why?
Image Analyst
Image Analyst 2023-3-1
Yes, you just load the workbook file into the "data" variable and then you never do anything with data. Plus on every iteration data is overwritten by the current workbook so at the very end you'll only have data from the very last workbook. If you want to do something with data, then do so. If you also want to save it for use later, outside the loop, then you'll need to save it somehow, like in a cell array.
data{k} = readtable(fullFileName);

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by