Import and Read data with several sheets

조회 수: 4 (최근 30일)
Oluwasogo
Oluwasogo 2024년 7월 16일
편집: dpb 2024년 7월 16일
Hello Everyone,
I am trying to use the line of code below to read my matrix data from an excel file. However, I get stuck from the the 2nd line of code, which takes forever to run and not complete. I am wondering if I am doing something wrong. Can some help with advice?
[~,sheet_name]=xlsfinfo('Gas.xlsx');
for k=1:numel(sheet_name)
data{k}=readmatrix('Gas.xlsx','Sheet',sheet_name{k},'Range','A2:IP176');
end

채택된 답변

dpb
dpb 2024년 7월 16일
편집: dpb 2024년 7월 16일
Hard to diagnose w/o the file, but try
sheets=sheetnames('Gas.xlsx');
for k=1:numel(sheets)
data{k}=readmatrix('Gas.xlsx','Sheet',sheets(k),'NumHeaderLines',1);
end

추가 답변 (2개)

Mathy
Mathy 2024년 7월 16일
Hi Oluwasogo,
The following code snippet will assist you in reading data from multiple Excel sheets:
Assumptions:
  • The desired data is stacked vertically.
  • The number of columns is consistent across all sheets.
% Importing Data from excel across multiple sheets and filenames.
filename = 'file.xlsx';
[~,sheet_name]=xlsfinfo(filename)
data_all = [];
for k=1:numel(sheet_name)
[data,TXT,RAW]=xlsread(filename,sheet_name{k})
% stack data vertically
data_all = [data_all ; data];
end
Hope this helps!
  댓글 수: 1
Stephen23
Stephen23 2024년 7월 16일
"Using 'readtable' can be more efficient for reading data from Excel files."
Really? Do you have a reference for this claim?

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


Ashutosh Thakur
Ashutosh Thakur 2024년 7월 16일
Hello Oluwasogo,
I understand that you are trying to read an Excel sheet and the performance issue might be due to the xlsinfo and readmatrix functions. Additionally, to get the names of the sheets in an Excel file, the sheetnames function is recommended instead of xlsinfo.
You can refer to the following documentation link for more information on sheetnames:
Please note that the sheetnames function will return a string array instead of a cell array. Additionally, you can preallocate the cell array such as data for better performance. The following lines of code can be used as a reference:
sheet_names = sheetnames('Filename.xlsx');
numSheets = numel(sheet_names)
data = cell(1, numSheets); % Preallocate cell array
for k = 1:numSheets
data{k} = readmatrix('Filename.xlsx', 'Sheet', sheet_names(k), 'Range', 'A2:IP176');
end
I hope this helps you!

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by