How to use PHPSpreadsheet in CodeIgniter 3 to read data from Excel (.xlsx and .xls) file?

Shimul picture Shimul · Feb 6, 2018 · Viewed 14.8k times · Source

Recently in one of my CodeIgniter based project, I need to read data from Excel file ( .xlsx and .xls ) and insert those data into MySQL. Unfortunately, I did not use PHPSpreadsheet before (as I did not require to work with Excel :( ).

So far what I did was, download the PHPSpreadsheet from Github and extract it to the root directory of my CodeIgniter Project.

enter image description here PHPSpreadsheet in CodeIgniter root directory.

enter image description here File Structure of PHPSpreadsheet.

So far I've tried to import the official docs example into my CI apps:

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    use PhpOffice\PhpSpreadsheet\IOFactory;
    class Welcome extends CI_Controller {
       function __construct() {
           parent::__construct();
       }

       public function index()
       {
           $inputFileType = 'Xlsx';
           $inputFileName = 'test.xlsx';
           $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
    /**  Load $inputFileName to a Spreadsheet Object  **/
          $spreadsheet = $reader->load($inputFileName);
          print_r( $spreadsheet );
    }
}

But it shows the following error!! enter image description here

Can anyone tell me how can I use PHPSpreadsheet in CodeIgniter to read data from Excel file and store them into MySQL database?

  • Thanks

Answer

Nathan Carter picture Nathan Carter · Feb 7, 2018

The easiest way to include PhpSpreadsheet is to use Composer - the documentation at https://phpspreadsheet.readthedocs.io/en/latest/ explains how to do this.

Otherwise you will need a PSR4 autoloader to load the class specified by your use statement or to include the files yourself. If you include files yourself, to read an Excel file you will need to include PhpSpreadsheet/src/PhpSpreadsheet/IOFactory.php