Ben
Ben

Reputation: 1839

Reading Excel file with multiple sheets

I have an Excel file which contains 4 sheets.

Each sheet has the same format but the data inside is different. For example:

sheet1:
              sub1 sub2 sub3

    person1    2    3     4
    person2    9    0     1
    person3    8    4     2

sheet2:

              sub1 sub2 sub3

    person1    5    7     8
    person2    1    3     7
    person3    4    1     3

Now, I know how to read the data for 1 sheet:

[data, titles] = xlsread(FileName, 'sheet1');

But when I don't know how many sheets I have in my document, how can I store all data from all sheets?

Upvotes: 3

Views: 8172

Answers (2)

Dev-iL
Dev-iL

Reputation: 24169

A for loop is unnecessary. The importdata function (introduced before R2006a) can handle this scenario with ease. For example, I had an excel file with 5 sheets containing data as below:

Sample data

As you can see, it contains text, numbers and blank spaces. On R2017b, calling

xlsData = importdata('name-of-file.xlsx');

results in a struct containing two fields: data (for numeric values, holding double arrays) and textdata (for text, holding cell arrays), each having fields that correspond to worksheet names in the Excel file.

Upvotes: 0

Dan
Dan

Reputation: 45752

You can use xlsfinfo to get a list of the sheets and then loop over that list:

[status,sheets] = xlsfinfo(FileName)

for s = 1:numel(sheets)
    ...
    [data,titles]=xlsread(FileName,sheets(s))
    ...
end

Upvotes: 5

Related Questions