Home » excel » php – how can i add new row in phpspreadsheet?

php – how can i add new row in phpspreadsheet?

Posted by: admin May 14, 2020 Leave a comment

Questions:

i have one small project [Billing Account] contains some math operations / values like [+/*-%]..
with deep search a lot of sites advise phpspreadsheet , i started to learn how use it by tutorials.

Q: how i add new row?

for example : when i click save button program will be save another record in
new row.

Code:

<?php

use PhpOffice\PhpSpreadsheet\Spreadsheet; 
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

require_once __DIR__ . '/phpoffice/phpspreadsheet/src/Bootstrap.php';


$spreadsheet = new Spreadsheet();
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Name:<input type="text" name="name">
    Age:<input type="text" name="age">
    <input type="submit" name="submit" value="Save">
</form>
</body>
</html>
<?php

$spreadsheet->getProperties()
->setCreator('root');

// New Worksheet
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('MySheet');


if(isset($_POST['submit'])){
$name = $_POST['name'];
$age = $_POST['age'];

 $sheet->setCellValue('A1',$name);
 $sheet->setCellValue('B1',$age);

$Writer = new Xlsx($spreadsheet);
$Writer->save('test.xlsx');

}
How to&Answers:

I think what you are looking for is insertNewRowBefore, you need a Worksheet class instance which is what you use most of the time to manipulate a particular active sheet.
I don’t realy know what else you need but follow this API docs

If you just want to add a value into a cell, simply use:

$cell = $sheet->getCellByColumnAndRow(colNumber(int), rowNumber(int));
$sheet->setCellValue('e.g A1', $cell->getValue());

Then again, explore the api, spreadsheet works in a rather weird manner.