Reputation: 674
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?
Upvotes: 11
Views: 20825
Reputation: 403
The accepted answer throws exception: "Column references should not be numeric."
For me works:
...
$row = 'A' . ($sheet->getHighestRow() +1);
$sheet->insertNewColumnBefore($row);
$sheet->setCellValue($row, 'Hello World again!');
...
Upvotes: 0
Reputation: 57141
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');
Upvotes: 18
Reputation: 575
Hello I think this issue came because of memory exhausted so increase your memory limit by php.ini file
like memory_limit = 256M
After increase memory limit , restart your apache
Upvotes: 0