PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 3, 2022

[FIXED] How to add new row on Excel using PHPSpreadsheet

 October 03, 2022     excel, php, phpexcel, phpspreadsheet     No comments   

Issue

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');


Answered By - Nigel Ren
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing