Opening multiple excelworksheets with stringnames from a cell

조회 수: 7 (최근 30일)
Thomas Koelen
Thomas Koelen 2015년 3월 24일
댓글: Thomas Koelen 2015년 3월 24일
I have a template file who's name is Template UTT, I load and read the file like this:
excelsheet = uigetfile('.xlsx','Select a template');
[num,txt,raw] = xlsread(excelsheet,'main');
In the excel sheet there is some data:
BEGIN_DATA
GS_L OECF DYNAMIC_RANGE
GS_R OECF DYNAMIC_RANGE
GS_U OECF DYNAMIC_RANGE
GS_D OECF DYNAMIC_RANGE
HOR_B UNIFORMITY
HOR_W UNIFORMITY
HOR_G UNIFORMITY
VER_B UNIFORMITY
VER_W UNIFORMITY
VER_G UNIFORMITY
END_DATA
The inputs in the first row between BEGIN_DATA and END_DATA corrosponds to a sheet in the complete excel file, So there are seperate sheets for
GS_L
GS_R
GS_U
GS_D
HOR_B
HOR_W
HOR_G
VER_B
VER_W
VER_G
I want to read each of these sheets induvidually and save data to a variable, or some other way of saving the data so I can read it somewere else in the program.
Now I know I can do this with a for loop and assignin and eval, but I keep reading everywere that this is not the way you should work.
It should look something like this:
[num,txt,raw] = xlsread(excelsheet,'main');
Where main is the main sheet of the whole file, but I want to read another sheet. I can't make it just read all possible sheets because there are different Templates with different names for the sheets.
Could you maybe help me in the right direction?
Kind regards,
Thomas Koelen

채택된 답변

Titus Edelhofer
Titus Edelhofer 2015년 3월 24일
Hi Thomas,
the loop is not bad, but assignin and eval are in this case, that's right. My suggestion would be to do something as follows:
[num,txt,raw] = xlsread(excelsheet, 'main');
% extract from txt your sheet names, e.g.
sheetNames = txt(:,1);
% loop over the sheetNames
for iSheet = 1:length(sheetNames)
[s_num, s_txt, s_raw] = xlsread(excelsheet, sheetNames{iSheet});
data.(sheetNames{iSheet}) = s_txt; % or s_num or whatever
end
This way you build up a structure, where the field names are given by the sheetNames. This works, as long as you have GS_L etc being valid variable names. If not, you could use containers.Map instead of a structure.
Titus
  댓글 수: 1
Thomas Koelen
Thomas Koelen 2015년 3월 24일
Thanks again..
I'm fairly new with Matlab and never really worked with a struct, this is the first time actually! This works way better than assignin and eval!
Kind regards
THomas

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import from MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by