The below code works for flat csv or txt files. It does a good job of reading all of the headers. Is there an easy way to make it work for xlsx files as well?
header_end = false;
header_count = 0;
% preallocate 50 rows of header text
header = cell(50, 1);
%% Loop through header lines
while ~header_end
%% Get a whole line from the file
aline = fgetl(FID);
%% Use a regular expression to look for the data block header
tokens = regexp(aline, ...
['(\d+)' ... % capture a number
'\s+!\s+' ... % followed by an !
'(\w+\s+)+'],... % and capture a series of strings
'tokens', 'warnings');
%% Parse data block header if found
if ~isempty(tokens) && numel(tokens{:}) == 2
% parse numeric token using string to double
num_datum = str2double(tokens{1}(1));
% parse variable string
varNameStr = deblank(tokens{1}(2));
names = strsplit(varNameStr{:});
%names = names{1};
% stop looping
header_end = true;
else
% Increment header line count and add new line
header_count = header_count+1;
header{header_count} = aline;
end
end