Blog
August 7, 2014 Marie H.

Importing Spreadsheets with PHPExcel

Importing Spreadsheets with PHPExcel

Photo by <a href="https://www.pexels.com/@tima-miroshnichenko" target="_blank" rel="noopener">Tima Miroshnichenko</a> on <a href="https://www.pexels.com" target="_blank" rel="noopener">Pexels</a>

PHPExcel is an awesome class for working with spreadsheets, you can download it here: https://phpexcel.codeplex.com/

It makes for very easy importing regardless of the format’s that are uploaded from a user. Below you can see a simple class with a public function for importing a spreadsheet; you will likely need to update some translation logic based on the spreadsheet you are working with.

<?php
class SpreadsheetImporter {

    public function import($file_name) {
        $objReader = PHPExcel_IOFactory::createReaderForFile($file_name);
        try {
            $objPHPExcel = $objReader->load($file_name);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($file_name,PATHINFO_BASENAME).'": '.$e->getMessage());
        }
        /*
            Get worksheet dimensions
        */
        $sheet         = $objPHPExcel->getSheet(0);
        $highestRow    = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        for ($row = 1; $row <= $highestRow; $row++) {
            $data = $sheet->rangeToArray(
                'A' . $row . ':' . $highestColumn . $row,
                NULL,
                TRUE,
                FALSE
            );
            /*
                Convert date to something human readable.
                PHPExcel stores dates as floating point numbers;
                ExcelToPHP() converts them to a Unix timestamp.
            */
            $date     = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP(
                            $sheet->getCellByColumnAndRow(4, $row)->getValue()));
            $fullname = $data[0][0];
            $email    = $data[0][2];
            $dept     = $data[0][3];
            $supe     = $data[0][5];
            $user     = explode(' ', $fullname);
            $user     = strtolower($user[0][0] . end($user));
            $this->add_new($fullname, $user, $email, $date, $dept, $supe);
        }
    }
}
?>

Example output — given a spreadsheet with one employee row:

Name: Jane Smith
User: jsmith
Email: jane.smith@example.com
Date: 2014-08-07
Dept: Engineering
Supervisor: Bob Jones

Note (Updated 2026-03-20): PHPExcel is abandoned. The maintained successor is PhpSpreadsheet. The API is nearly identical — replace PHPExcel_IOFactory with \PhpSpreadsheet\IOFactory and PHPExcel_Shared_Date with \PhpSpreadsheet\Shared\Date.