Using a 'for' Loop to Pass in Excel Files

6 views (last 30 days)
Hi, all. Let me start with the code and I'll explain the issue second:
for k = 1:size(excel_files,2)
C = cellstr(excel_files(k));
file_open = fopen('C(k)','a');
excel_read = xlsread(file_open(k));
excel_write = xlswrite('Master_File.xlsx');
file_close = fclose(file_open(k));
end
The variable 'excel_files' is a 1x11 cell whose entries look like this on the command window: '16Jun18 Exp_Results.xlsx'
My goal is to use the loop to read the data from all 11 Excel files, one at a time, and append the newest data set to 'Master_File.xlsx'. There are two errors I keep getting under different circumstances. If I enter:
file_open = fopen(C(k),'a')
I get the error: "Error using fopen First input must be a file name or a file identifier."
If I enter the code as originally stated, I get the error: "Error using xlsread (line 125) File name must be a character vector."
I was under the impression the 'cellstr' function would remedy the issue, but that isn't the case. Do the apostrophes around C(k) not transfer through to the file name? Any help would be greatly appreciated, and if I was unclear at all, please let me know so I can add amplifying information.
Thank you!

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 19 Jun 2018
No need to use fopen() and fclose() to read Excel file.
Assume "excel_files" is a 1x11 cell, each contains an Excel file name such as '16Jun18 Exp_Results.xlsx'.
Assume the first sheet of each Excel file contains all numerical data with the same number of columns
Data=[];
for k=1:length(excel_files)
Data=[Data;xlsread(excel_files{k})];
end
xlswrite('Master_File.xlsx',Data)
  2 Comments
Jeremy
Jeremy on 19 Jun 2018
The inherent simplicity is what you wrote is amazing; I tend to brute force things versus finding the more eloquent solution.
One question: you say that it is unnecessary to use fopen with an Excel file. The reason I initially chose fopen was because I can add the 'a' modifier to it and have new data appended to the end of the existing Excel file. Is there a better way to go about making that happen?
Fangjun Jiang
Fangjun Jiang on 19 Jun 2018
Mathworks provided the xlsread() and xlswrite() function for easy access of Excel file. It has nothing to do with fopen() and fclose(). You could use xlswrite() to write to the same Excel file multiple times and achieve the effect of appending by specifying the location of the Excel file. But that is less efficient than the concatenation of array data in MATLAB and then write the Excel file once.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!