当我添加新行时,它会覆盖我添加的最后一行


When I add a new row, it overwrites the last I added

我正在使用PHPExcel将Excel(xlsx)文件加载到我的html页面中。

我设法使用下面的表格添加了一个新表格,但不幸的是,我添加的每一行都会覆盖第一行。有没有一种方法可以刷新,这样我就不会覆盖以前添加的值?

这是我添加新行的表格:

<form action="" method="post" id="AddForm" name="AddForm">
<input type="text" id="company" name="company" value="Enter new name" />
<input type="submit" id="save" name="add" value="add"/>
</form>

下面是我用来加载/显示/添加新行的代码

    <?php
    require_once '../inc/phpexcel/Classes/PHPExcel.php';
    require_once '../inc/phpexcel/Classes/PHPExcel/IOFactory.php';
    $objPHPExcel = PHPExcel_IOFactory::load("myExcelFile.xlsx");
    $objWorksheet = $objPHPExcel->getActiveSheet();
    //add the new row
    $num_rows = $objPHPExcel->getActiveSheet()->getHighestRow();
    $objWorksheet->insertNewRowBefore($num_rows + 1, 1);
    $name = isset($_POST['name']) ? $_POST['name'] : '';
    if($submit){
//SAVING THE NEW ROW - on the last position in the table
    $objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$name);
    }
    //display the table
    echo '<table>'."'n";
    echo '<thead>
    <tr>
        <th>Company Name</th>
    </tr>
    </thead>'."'n";
    echo '<tbody>'."'n";
    foreach ($objWorksheet->getRowIterator() as $row) {
    echo '<tr>'."'n";
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);
    foreach ($cellIterator as $cell) {
    echo '<td>'.$cell->getValue().'</td>'."'n";
    }
    echo '</tr>'."'n";
    }
    echo '</tbody>'."'n";
    echo '</table>'."'n";
    ?>

我找到了解决方案:在循环中,需要在每次请求后保存文件:

$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$company_name);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('myExcelFile.xlsx');
echo date('H:i:s') . " Write to Excel2007 format'n";