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

时间:2012-09-13 12:55:59

标签: php phpexcel

我正在使用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";
    ?>

1 个答案:

答案 0 :(得分:0)

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

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