15

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

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

如果是这样,我该如何为excel文件做到这一点?

4

2 回答 2

34

假设这个设置:

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

您可以像这样获得行数:

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

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

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

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

于 2012-07-10T15:45:17.257 回答
6

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

<?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";
        ?>
于 2012-09-14T02:48:05.537 回答