2020-11-03 MATLAB App Designer—讀取Excel信息
背景
在excel文件里存放有數(shù)據(jù),目前需要讀取該.xlsx內(nèi)的多個(gè)工作簿所包含的數(shù)據(jù),并將讀取的數(shù)據(jù)設(shè)置成table格式
要用到的函數(shù)
sheetnames(ProjectPath); %?讀取Excel文件的工作簿名稱 % 為?str?形式
?readtable(ProjectPath,'ReadVariableNames',true,'Sheet',SheetName);
%?ProjectPath % 文件絕對路徑
%?SheetName % 需要讀取的工作簿名稱
函數(shù)使用
% 首先獲取excel文件內(nèi)的工作簿名稱 %?ExcelBookList_Excel
ExcelBookList_Excel = sheetnames(app.inData.ProjectPath); % 讀取Excel文件的工作簿名稱 % 為 str 形式
% 如果存在以下工作簿就讀取該工作簿的數(shù)據(jù)
ExcelBookList = {'ColNameList';'LimintValueData';'InitialValue';'CacluateSymData'; % 為cell 形式?
? ? ? ? ? ? ? ? ? ? ? ? ? ? 'IntervalcolName';'PreTreatMentPlan';'PreWorkflow';'Info';
? ? ? ? ? ? ? ? ? ? ? ? ? ? 'Template';'MainFileData';'SensorsData';'PathData'};
%?對每個(gè)工作簿采用for循環(huán)單獨(dú)讀取
for ii =? 1 : length( ExcelBookList?)
? ? ? ? ?try eval( strcat(?ExcelBookList{ ii }?= readtable( ProjectPath,' ,?39 , 'ReadVariableNames' , 39 , ', true,' , 39 , 'Sheet' , 39 , ',' , 39 , ExcelBookList{ ii }? , 39 , ');'? ) );
? ? ? ? ??catch;?disp(strcat('ERROR!!!讀取失?。?#39;,32,ExcelBookList{ ii }?));
? ? ? ? ? ?end
end
進(jìn)階加速
采用for循環(huán)讀取很耗時(shí)間,想了個(gè)辦法加速讀取數(shù)據(jù),使用下面的函數(shù),數(shù)據(jù)保存在inData中,為struct結(jié)構(gòu)形式。
實(shí)測該方案能節(jié)約for循環(huán)下的一半左右的時(shí)間。
cell2mat(cellfun( @(x) xifun_readtable( ?ProjectPath , x ),ExcelBookList,'UniformOutput',false))
function [ Message ] = xifun_readtable(?ProjectPath ,x ) % 讀取工程文件指定工作簿
? ? ? ? ? ? ? ? try eval(strcat('inData.',x,'=readtable(ProjectPath,',...
? ? ? ? ? ? ? ? ? ? ? ? 39,'ReadVariableNames',39,',true,',39,'Sheet',39,',',39,x,39,');' ));
? ? ? ? ? ? ? ? Message = 1;
? ? ? ? ? ? ? ? catch;Message = 0;? disp(strcat('ERROR!!!',32,x));
? ? ? ? ? ? ? ? end
end