SpreadSheet-Coding.com

PhpSpreadsheet

Create Xlsx Files With Grouped Or Outlined Rows

March 13, 2022

Group rows of xlsx files in PhpSpreadsheet, a quick process to outline a cluster of related rows.

Requirements:

Step 1.

Setup dependencies.

composer.json
{
    "require": {
        "phpoffice/phpspreadsheet": "^1.3"
    }
}

Step 2.

Install phpspreadsheet.

command line
$ composer install

Step 3.

Create a new PHP file, and start coding.

create-xlsx-files-with-grouped-or-outlined-rows.php
<?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);
}

// Group/outline rows 4-6
$spreadsheet->getActiveSheet()->getRowDimension('4')->setOutlineLevel(1);
$spreadsheet->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1);
$spreadsheet->getActiveSheet()->getRowDimension('6')->setOutlineLevel(1);

// Write a new .xlsx file
$writer = new Xlsx($spreadsheet);

// Save the new .xlsx file
$writer->save('create-xlsx-files-with-grouped-or-outlined-rows.xlsx');

Test.

Run the following codes.

command line
$ php create-xlsx-files-with-grouped-or-outlined-rows.php

Result.

Open the generated file create-xlsx-files-with-grouped-or-outlined-rows.xlsx.

Check grouped rows.

References: