You are here

protected function Spreadsheet::loadWorksheet in Migrate Spreadsheet 2.0.x

Same name and namespace in other branches
  1. 8 src/Plugin/migrate/source/Spreadsheet.php \Drupal\migrate_spreadsheet\Plugin\migrate\source\Spreadsheet::loadWorksheet()

Loads the worksheet.

Return value

\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet The source worksheet.

Throws

\Drupal\migrate\MigrateException When it's impossible to load the file or the worksheet does not exist.

1 call to Spreadsheet::loadWorksheet()
Spreadsheet::initializeIterator in src/Plugin/migrate/source/Spreadsheet.php
Initializes the iterator with the source data.

File

src/Plugin/migrate/source/Spreadsheet.php, line 193

Class

Spreadsheet
Provides a source plugin that migrate from spreadsheet files.

Namespace

Drupal\migrate_spreadsheet\Plugin\migrate\source

Code

protected function loadWorksheet() : Worksheet {
  $config = $this
    ->getConfiguration();

  // Check that the file exists.
  if (!file_exists($config['file'])) {
    throw new MigrateException("File with path '{$config['file']}' doesn't exist.");
  }

  // Check that a non-empty worksheet has been passed.
  if (empty($config['worksheet'])) {
    throw new MigrateException('No worksheet was passed.');
  }

  // Load the workbook.
  try {
    $file_path = $this->fileSystem
      ->realpath($config['file']);

    // Identify the type of the input file.
    $type = IOFactory::identify($file_path);

    // Create a new Reader of the file type.

    /** @var \PhpOffice\PhpSpreadsheet\Reader\BaseReader $reader */
    $reader = IOFactory::createReader($type);

    // Advise the Reader that we only want to load cell data.
    $reader
      ->setReadDataOnly(TRUE);

    // Advise the Reader of which worksheet we want to load.
    $reader
      ->setLoadSheetsOnly($config['worksheet']);
    $workbook = $reader
      ->load($file_path);
    return $workbook
      ->getSheet(0);
  } catch (\Exception $e) {
    $class = get_class($e);
    throw new MigrateException("Got '{$class}', message '{$e->getMessage()}'.");
  }
}