Using a 'for' Loop to Pass in Excel Files
5 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Fangjun Jiang
2018-6-19
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 个评论
Fangjun Jiang
2018-6-19
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.
更多回答(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!