Create Excel Files With Page Margins Settings In PHP Using PHPSpreadSheet

Before printing an xlsx file, there are options to align it’s worksheet to make it look finer when printed. These are the adjustments on the white spaces at the top, bottom, left, and right sides of the document, these are commonly known as page margins.

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 top page margin
$sheet->getPageMargins()->setTop(1);

// Set right page margin
$sheet->getPageMargins()->setRight(0.75);

// Set left page margin
$sheet->getPageMargins()->setLeft(0.75);

// Set bottom page margin
$sheet->getPageMargins()->setBottom(1);

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

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

Test.

Run the following codes.

$ php create-xlsx-files-with-page-margins-settings.php

Result.

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

// Set top page margin
$sheet->getPageMargins()->setTop(1);

// Set right page margin
$sheet->getPageMargins()->setRight(0.75);

// Set left page margin
$sheet->getPageMargins()->setLeft(0.75);

// Set bottom page margin
$sheet->getPageMargins()->setBottom(1);

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 *