使用PHPExcel添加新行?

时间:2012-07-10 15:39:30

标签: php phpexcel

如何使用PHPExcel将新行添加到现有.xls文件?

我是否必须计算已存在的行数?

如果是这样,我该如何为excel文件执行此操作?

2 个答案:

答案 0 :(得分:29)

假设这样设置:

$objPHPExcel = PHPExcel_IOFactory::load("foo.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();

您可以获得如下行数:

$num_rows = $objPHPExcel->getActiveSheet()->getHighestRow();

在此之后,您可以使用以下语句来查看插入行:

$objWorksheet->insertNewRowBefore($num_rows + 1, 1);

这会在$num_rows之前添加1个新行。

答案 1 :(得分:5)

上面的示例仅添加一个空白行。以下示例添加来自表单的数据。

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