Read Excel Files In PHP Using PHPSpreadSheet’s IOFactory Class

Posted

in

by

Aside from it’s specified xlsx reader class, the IOFactory class can also create a reader, this is more handy if there are different file types to handle, as it can create a reader for all the supported files, thus using a particular reader for a particular supported file is not needed anymore.

Requirements:

  • Composer
  • PHP 7.2 or newer

Step 1.

Setup dependencies.

{
    "require": {
        "phpoffice/phpspreadsheet": "^1.3"
    }
}

Step 2.

Install phpspreadsheet.

$ composer install

Step 3.

Create a new PHP file, and start coding.

<?php

// Autoload dependencies
require 'vendor/autoload.php';

// Import the IOFactory class
use \PhpOffice\PhpSpreadsheet\IOFactory;

// Full path of the file to be indentified
$inputFileName = 'create-xlsx-files.xlsx';

// Identify the file type using the IOFactory object
$inputFileType = IOFactory::identify($inputFileName);

// Create the reader object
$reader = IOFactory::createReader($inputFileType);

// Load the file to read
$spreadsheet = $reader->load($inputFileName);

// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();

/**
 * Get the value of column A, row 1 using the
 * combination of the column letter and row number.
 */
echo $sheet->getCell('A1')->getValue();

echo PHP_EOL;

/**
 * Get the value of column A, row 1 using the
 * combination of the column number and row number.
 */
echo $sheet->getCellByColumnAndRow('1', '1')->getValue();

Test.

Command line testing.

$ php read-xlsx-files-using-ioactory-class.php

Result.

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Tutorials

Web Dev Tutorials