Create Excel Files With Rows And Columns Repeat Settings In PHP Using PHPSpreadSheet

Posted

in

by

To save some time coding same cell value/s for each page of a spreadsheet, use the function setRowsToRepeatAtTopByStartAndEnd() when creating xlsx file in PhpSpreadsheet to repeat row/s on every printed page.

To clearly demostrate the result of this tutorial, the Setting Printing Breaks in PhpSpreadsheet Tutorial will be used.

Requirements:

  • Composer
  • PHP 7.2 or newer

Step 1.

Setup dependencies.

{
    "require": {
        "phpoffice/phpspreadsheet": "^1.3"
    }
}

Step 2.

Install phpspreadsheet.

$ composer install

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

// Set cell A1 with the "Hello World !" string value
$sheet->setCellValue('A1', 'Hello World !');

// Set cell A5 with the "First Page !" string value
$sheet->setCellValue('A5', 'First Page !');

// Set a row break on 'A10'
$sheet->setBreak('A10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW);

// Set cell A15 with the "Second Page !" string value
$sheet->setCellValue('A15', 'Second Page !');

// Repeat 'A1' on all pages
$sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);

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

// Save the new .xlsx file
$writer->save('create-xlsx-files-with-rows-and-columns-repeat-settings.xlsx');

Test.

Run the following codes.

$ php create-xlsx-files-with-rows-and-columns-repeat-settings.php

Result.

Open the generated file create-xlsx-files-with-rows-and-columns-repeat-settings.xlsx.

Click View.

Click Page Layout.

// Set cell A1 with the "Hello World !" string value
$sheet->setCellValue('A1', 'Hello World !');

// Set cell A5 with the "First Page !" string value
$sheet->setCellValue('A5', 'First Page !');

// Set a row break on 'A10'
$sheet->setBreak('A10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW);

// Set cell A15 with the "Second Page !" string value
$sheet->setCellValue('A15', 'Second Page !');

// Repeat 'A1' on all pages
$sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Tutorials

Web Dev Tutorials