Search code examples
phpexcelphpexcelphpspreadsheet

How to add new row on Excel using PHPSpreadsheet


Hi I'm new to this library called PHPSpreadsheet. I tried reading it's docs but I can't understand it.

I want to insert a new row on an existing Excel File and here is what I have so far:

<?php 

require '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$inputFileName = 'Excel/hello.xlsx';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);

$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Updated');

$writer = new Xlsx($spreadsheet);
$writer->save('../controller/excel/hello.xlsx');

?>

This inserts new data on the 'hello.xsls' file replacing the cell's previous data. How can I make it write data into a new row?


Solution

  • To create a new row, you need to call insertNewRowBefore() with the row number you want to insert before...

    $sheet = $spreadsheet->getActiveSheet();
    $sheet->insertNewRowBefore(1);
    $sheet->setCellValue('A1', 'Updated');
    

    You can also call it with a number of rows to insert, the default is 1.

    If you want to append a row, you can call getHighestRow() to find the last row and add 1 to it for the new row. Also change the hard coding of the column in the setCellValue() call to use this row as well...

    $sheet = $spreadsheet->getActiveSheet();
    $row = $sheet->getHighestRow()+1;
    $sheet->insertNewRowBefore($row);
    $sheet->setCellValue('A'.$row, 'Updated');