PHPExcel:逐行读取Excel文件

时间:2017-03-29 12:32:41

标签: php phpexcel netbeans-8

我需要一些帮助。我想要实现的是使用PHPExcel逐行读取Excel文件。我能够读取文件并获取数据,但无法弄清楚如何逐行读取。这是我的代码。

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 />';
        }
    }       
    ?

我是有人可以帮助我的。

1 个答案:

答案 0 :(得分:4)

尝试使用此代码代替for循环

$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 />';
 } 

已编辑在内部foreach循环周围添加{}

已编辑:添加第二个选项 - 用于创建表格数据

这适用于我并创建一个表格,使用Excel工作表名称作为表格标题

$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;