SpreadSheet-Coding.com

PhpSpreadsheet

Set Metadata Of Excel Files In PHP Using PHPSpreadSheet

July 11, 2020

Create a new xlsx file and set it’s metadata properties.

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.

set-metadata-of-xlsx-files.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();

// Set the properties or metadata of the file
$spreadsheet->getProperties()
    ->setCreator("Name of the creator")
    ->setLastModifiedBy("The creator")
    ->setTitle("Title of the xlsx file")
    ->setSubject("Subject of the xlsx file")
    ->setKeywords("Keywords of the xlsx file")
    ->setCategory("Category of the xlsx file")
    ->setDescription("Description of the xlsx file.")
;

// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();

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

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

// Save the new .xlsx file
$writer->save('set-metadata-of-xlsx-files.xlsx');

Test.

Run the following codes.

command line
$ php set-metadata-of-xlsx-files.php

Result.

Check the property of the generated file set-metadata-of-xlsx-files.xlsx.

References: