Adding a new row with PHPExcel?

前端 未结 2 1677
执念已碎
执念已碎 2020-12-18 21:41

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 a

相关标签:
2条回答
  • 2020-12-18 21:45

    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";
            ?>
    
    0 讨论(0)
  • 2020-12-18 22:07

    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.

    0 讨论(0)
提交回复
热议问题