How to open multiple .dat files in Matlab and save them in the given name as .xlsx file per sheet

2 views (last 30 days)
I attached 10 .dat files. Each of the files contain 40 years hourly data. Kindly help me with the matlab codes to open and save the in .xlsx formats using the file names individually in a file sheet by sheet. I will also use the codes for the other 30 files. Thanks.
Ojo O. S

Accepted Answer

Image Analyst
Image Analyst on 31 Jul 2021
For some reason, I'm having trouble unzipping your data. Window10 won't allow it. In the meantime, try this:
% Specify the folder where the files live.
myFolder = 'D:\data files';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.dat'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
numFiles = length(theFiles)
Result = zeros(numFiles, 1);
for k = 1 : numFiles
baseFileName = theFiles(k).name;
[~, baseFileNameNoExt, ext] = fileparts(baseFileName);
inputFullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', inputFullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
data = readmatrix(inputFullFileName, 'x.);
outputFullFileName = fullfile(myFolder, baseFileNameNoExt, '.xlsx');
fprintf(1, 'Now writing %s\n', outputFullFileName);
xlswrite(outputFullFileName, data);
end
  10 Comments
Image Analyst
Image Analyst on 1 Aug 2021
Then simply set up your outputFullFileName, BEFORE the for loop. Then it will save into the same workbook all the time. Of course to precent overwriting you're going to have to change the cell reference, like
outputFullFileName = 'whatever.xlsx'
nextRow = 1;
for k = 1 : numFiles
baseFileName = theFiles(k).name;
[~, baseFileNameNoExt, ext] = fileparts(baseFileName);
inputFullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', inputFullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
data = readmatrix(inputFullFileName, 'x.);
cellReference = sprintf('A%d', nextRow);
fprintf(1, 'Now writing %s\n', outputFullFileName);
xlswrite(outputFullFileName, data);
% Increment the next row to be just below this data
nextRow = nextRow + size(data, 1);
end

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!