Create Excel Files With Center On Page Settings In PHP Using PHPSpreadSheet

At times, when creating an xlsx file, there is a need to put the data in center or in the middle of the page. This can be achieved by the use of Center on page options under the page setup.

With PhpSpreadsheet, there is the function setHorizontalCentered() for centering horizontally, and the function setVerticalCentered() for centering vertically.

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 page horizontally centered
$spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);

// Set page vertically centered
$spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(true);

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

// Save the new .xlsx file
$writer->save('create-xlsx-files-with-center-on-page-settings.xlsx');

Test.

Run the following codes.

$ php create-xlsx-files-with-center-on-page-settings.php

Result.

Open the generated file create-xlsx-files-with-center-on-page-settings.xlsx.

// Set page horizontally centered
$spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);

// Set page vertically centered
$spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(true);

Default settings.

References:


Posted

in

by

Tags:

Leave a Reply

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

Leave a Reply

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