Skip to content

Last Sheet is alway set as the Active Sheet upon loading the File #2666

@eXsio

Description

@eXsio

This is:

- [X] a bug report
- [ ] a feature request
- [ ] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet)

What is the expected behavior?

According to the documentation Worksheet::getActiveSheet() should always return "the one that will be active when the workbook is opened in MS Excel (or other appropriate Spreadsheet program)."

What is the current behavior?

Currenty, the last Sheet is always marked as the Active Sheet after the file was loaded:

  1. Worksheet:676 iterates over the file's Sheets
  2. Worksheet:713 loads conditional styles for the currently processed Sheet
  3. ConditionalStyles:36 delegates the loading to the setConditionalStyles method
  4. ConditionalStyles:174 calls Worksheet::getStyle method
  5. Worksheet:1422 calls setActiveSheetIndex method

Assuming that all the Sheets are always loaded and that they are loaded in the order of the file's Sheets, the last Sheet in the file will always be set as the Active Sheet.

This functionality was working correctly in version 1.7.0 which I'm moving from. I've tried to downgrade to 1.15.0 but the issue is also there, so it's been in the code for quite some time. Versions below 1.15.0 are not compatible with PHP 8.0 so I can't go lower. This is a major blocker for me.

The root cause for me is that get getStyle method changes the Active Sheet Index. Generally methods that start with "get" shouldn't change the state of any objects.

Proposed solutions:

  1. Change the getStyle method to not change the data state
  2. Detect and cache the Active Sheet Index prior to any loading and re-set it once the load has been completed

What are the steps to reproduce?

Please provide a Minimal, Complete, and Verifiable example of code that exhibits the issue without relying on an external Excel file or a web server:

<?php

require __DIR__ . '/vendor/autoload.php';

// Load Spreadsheet from file that contains multiple Sheets, and the Active Sheet Index in the file != Last Sheet Index of the file
$spreadsheet = IOFactory::load($filename);

//Load the Active Sheet - it should be the actually Active Sheet, but instead it is the Last Sheet
 $worksheet = spreadsheet->getActiveSheet();

### Which versions of PhpSpreadsheet and PHP are affected?
- 8.0
- 8.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions