How to use for loop with xlsread to read multiple sheets in an excel file

조회 수: 8 (최근 30일)
mht6
mht6 2020년 3월 6일
댓글: Sindar 2021년 2월 20일
I am trying to read the same cells of data from different sheets in a single excel file.
I would prefer to use xlsread if possible. Additionally, the sheets are named not numbered.
Thank you

답변 (1개)

Sindar
Sindar 2020년 3월 6일
from the documentation:
num = xlsread(filename,sheet,xlRange) %reads from the specified worksheet and range.
so, just loop over the sheets (with sheetnames):
xlRange = 'B2:C3';
sheets = sheetnames(filename);
for ind=1:length(sheets)
num(ind) = xlsread(filename,sheets(ind),xlRange)
end
  댓글 수: 2
Kaushik Senguttuvan
Kaushik Senguttuvan 2021년 2월 20일
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
Error in AngDpn_Si_OPV (line 13)
num(ind) = xlsread(filename,sheets(ind))
This error comes. Any help would be great
Sindar
Sindar 2021년 2월 20일
You need xlRange to be sure it finds the same amount of data in each sheet. Additionally, I missed explaining that you'll need to do more careful indexing depending on the size of the data. The lines work for scalar data, but different shapes need changes:
Column data
num(:,ind) = xlsread(filename,sheets(ind),xlRange);
Row data
num(ind,:) = xlsread(filename,sheets(ind),xlRange);
matrix data
num(:,:,ind) = xlsread(filename,sheets(ind),xlRange);
Or, you can use cells which will always work but are more of a pain to deal with after:
num{ind} = xlsread(filename,sheets(ind),xlRange);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by