phpexcelphpexcelphpexcelreaderphpexcel-1.8.0

How do I use PHPExcel to read data from an Excel file?


I want to read data from an Excel file in PHP so that I can process the data and insert it into a DB.
Looking around SO, it looks like PHPExcel is the premier library for this task.

I went to the PHPExcel GitHub page (https://github.com/PHPOffice/PHPExcel), but I cannot figure out how to actually use the library. There are a ton of example files and none of the ones I looked at seem to match the simple use case I'm looking for.
Furthermore, I cannot even figure out which files from the GitHub page I even need to download and what the folder structure for the include file(s) needs to be.

As such, given the way the GitHub page linked above is structured now (for v1.8), what files do I need to download and what is a simple code example that allows me to provide a path to an Excel file and read the data from the file?


Solution

  • Mark Baker was extremely helpful in guiding me to the right answer. I don't use Composer with PHP (I should probably learn), but given that, in order to get this to work I went to the GitHub page for PHPExcel (https://github.com/PHPOffice/PHPExcel), clicked the green Clone and download button, and then the Download ZIP link.

    After unzipping the file, I got a folder called PHPExcel-1.8. I moved that folder to the same folder as both the Excel file I wanted to read (in my code below test.xlsx) and the PHP file that has the code below.

    The key to getting it to work was inputting the correct path to the IOFactory.php file. It may seem simple to some, but it was tripping me up.

    Given the above and Mark Baker's comments, the following code worked perfectly for me (note the commented parts):

    <?php
    
      //Had to change this path to point to IOFactory.php.
      //Do not change the contents of the PHPExcel-1.8 folder at all.
      include('PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');
    
      //Use whatever path to an Excel file you need.
      $inputFileName = 'test.xlsx';
    
      try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
      } catch (Exception $e) {
        die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . 
            $e->getMessage());
      }
    
      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow();
      $highestColumn = $sheet->getHighestColumn();
    
      for ($row = 1; $row <= $highestRow; $row++) { 
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
                                        null, true, false);
    
        //Prints out data in each row.
        //Replace this with whatever you want to do with the data.
        echo '<pre>';
          print_r($rowData);
        echo '</pre>';
      }