Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new row with PHPExcel?

Tags:

php

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?

like image 419
Novak Avatar asked Jul 10 '12 15:07

Novak


2 Answers

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.

like image 151
Daniel Li Avatar answered Oct 06 '22 22:10

Daniel Li


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";
        ?>
like image 44
Faraderegele Avatar answered Oct 06 '22 22:10

Faraderegele