Novak
Novak

Reputation: 2768

Adding a new row with PHPExcel?

How can I add a new row to an existing .xls file using PHPExcel?

Do I have to calculate the number of rows that already exist?

If so, how can I do that for an excel file?

Upvotes: 15

Views: 42846

Answers (2)

Daniel Li
Daniel Li

Reputation: 15399

Assuming this setup:

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

You can get the number of rows like so:

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

Following this, you can look into inserting a row by using the following statement:

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

This adds 1 new row before $num_rows.

Upvotes: 34

Faraderegele
Faraderegele

Reputation: 187

The example above only adds a blank row. The example below adds data coming from a 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";
        ?>

Upvotes: 6

Related Questions