Here’s a swift technique to attach additional rows in xlsx files, learn how to insert rows in PhpSpreadsheet.
Requirements:
- Composer
- PHP 7.2 or newer
Result without inserting new rows.
Step 1.
Setup dependencies.
{
"require": {
"phpoffice/phpspreadsheet": "^1.3"
}
}
composer.json
Step 2.
Install phpspreadsheet.
$ composer install
command line
Step 3.
Create a new PHP file, and start coding.
<?php
// Autoload dependencies
require 'vendor/autoload.php';
// Import the core class of PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
// Import the Xlsx writer class
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Retrieve the current active worksheet
$sheet = $spreadsheet------->getActiveSheet();
/**
* Loop through 'Column A - D'.
*/
foreach (range('A', 'D') as $letter) {
// Set some data to 'Column A - D' of 'Row 5'
$sheet->setCellValue($letter . '5', 'Column ' . $letter);
}
/**
* Insert 2 new rows before row 1.
*
* The created data above from row 2
* will now be moved to row 7.
*/
$spreadsheet->getActiveSheet()->insertNewRowBefore(1, 2);
$sheet->setCellValue('A1', 'New A1');
$sheet->setCellValue('A2', 'New A2');
// Write a new .xlsx file
$writer = new Xlsx($spreadsheet);
// Save the new .xlsx file
$writer->save('insert-rows-in-xlsx-files.xlsx');
insert-rows-in-xlsx-files.php
Test.
Run the following codes.
$ php insert-rows-in-xlsx-files.php
command line
Result.
Open the generated file insert-rows-in-xlsx-files.xlsx.
Leave a Reply