Search code examples
phpphpexcelnetbeans-8

PHPExcel: Read Excel File Line by Line


I need some help. What I am trying to achieve is to read Excel file line by line using PHPExcel. I am able to read the file and also get the data, but can't figure it out how to read it line by line. Here is my code.

require_once ('../src/Classes/PHPExcel.php');

    $excel_path = '../' . $_SESSION['excel_path'];

    try {
        $inputFileType = PHPExcel_IOFactory::identify($excel_path);
        $excelReader = PHPExcel_IOFactory::createReaderForFile($excel_path);
        $excelObject = $excelReader->load($excel_path);
    } catch (Exception $ex) {
        die('Error loading file"' . pathinfo($excel_path, PATHINFO_BASENAME) . '": ' . $ex->getMessage());
    }

    $sheet = $excelObject->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();

    for ($row = 1; $row <= $highestRow; $row++) {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . 
                $row, NULL, TRUE, FALSE);
        foreach ($rowData as $k) {
            echo $k[0].'<br />';
        }
    }       
    ?

I was that someone could help me.


Solution

  • Try this code in place of your for loop

    $rows = $sheet->rangetoArray('A1:'.$highestColumn . $highestRow, NULL, True, True, False);
    foreach ($rows as $row => $cols) {      
        $line = '';
        foreach($cols as $col => $cell){
            $line .= $cell." ... "; // ... or some other separator
        }
        echo rtrim($line,'. ').'<br />';
     } 
    

    Edited To add {} around inner foreach loop

    Edited: Adding 2nd option - for creating tabular data

    This works for me and creates a table, using the excel sheet name as the table caption

    $sheetname = $sheet->getTitle();
    $start=1;
    $table = "<table><caption>$sheetname</caption>";
    $rows = $sheet->rangetoArray('A'.$start.':'.$highestColumn . $highestRow, NULL, True, True, False);
    foreach ($rows as $row => $cols) {      
        $line = '<tr class="'.$row.'">';
        foreach($cols as $col => $cell){
            $line .= "<td>".$cell."</td>"; // ... or some other separator           
        }
        if($row == 0) $line = str_replace("td>","th>", $line);
        $table .= $line.'</tr>';
     } 
    $table .= "</table>";.
    
    echo $table;