1

How to get sheet 2 in Phpspreadsheet? I've just seen getActiveSheet(). is there other ways to get other sheet in a worksheet?

angelo
  • 13
  • 1
  • 4

2 Answers2

4

Yes, there are other methods to get a sheet.

Here is the code to get a sheet by name.

$spreadsheet->getSheetByName('sheetNameHere');

Also, you can get the sheet using the index number (starts with 0) like follows.

$spreadsheet->getSheet(0);
Garrett Burke
  • 123
  • 2
  • 9
2

This is example on how to read content from excel file with multiple sheet. First, we count the sheet has been created in that excel file. Then loop through the sheet and get contents of each sheet. Then, convert the sheet content to array so that we can display the content clearly to be used later according to our convenience.

$sheetCount = $spreadsheet->getSheetCount(); 

for ($i = 0; $i < $sheetCount; $i++) 
{
    $sheet = $spreadsheet->getSheet($i);
    $sheetData = $sheet->toArray(null, true, true, true);
    var_dump($sheetData);
 }

Example of var_dump of $sheetData:

sheet1

array(1) 
{
[1]=>
      array(1) 
      {
       ["A"]=>string(7) "sheet_1"
      }
}

sheet2

array(1) 
{
 [1]=>
      array(1) 
      {
        ["A"]=> string(7) "sheet_2"
       }
}
Premlatha
  • 1,676
  • 2
  • 20
  • 40
  • Do you want write to or read from excel? If you want to write, here is the link for you. https://stackoverflow.com/questions/54801141/write-to-multisheet-excel-using-phpspreadsheet-in-php/54882017#54882017. – Premlatha Mar 08 '19 at 01:36