Preselect different default styles of a spreadsheet when creating an xlsx file, set font to ‘Arial’, or ‘Verdana’, or any available font, change font size to a bigger or a smaller one, make the font bold, italic, or underlined. All these settings are attainable when coding with PhpSpreadsheet.
Requirements:
- Composer
- PHP 7.2 or newer
Step 1.
Setup dependencies.
{
"require": {
"phpoffice/phpspreadsheet": "^1.3"
}
}
composer.json
Step 2.
Install phpspreadsheet.
$ composer install
command line
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();
// Set default font type to 'Verdana'
$spreadsheet->getDefaultStyle()->getFont()->setName('Verdana');
// Set default font size to '12'
$spreadsheet->getDefaultStyle()->getFont()->setSize(12);
// Set default font style to italic
$spreadsheet->getDefaultStyle()->getFont()->setItalic(true);
// 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('create-xlsx-files-with-default-style-settings.xlsx');
create-xlsx-files-with-default-style-settings.php
Test.
Run the following codes.
$ php create-xlsx-files-with-default-style-settings.php
command line
Result.
Open the generated file create-xlsx-files-with-default-style-settings.xlsx.
// Set default font type to 'Verdana'
$spreadsheet->getDefaultStyle()->getFont()->setName('Verdana');
// Set default font size to '12'
$spreadsheet->getDefaultStyle()->getFont()->setSize(12);
// Set default font style to italic
$spreadsheet->getDefaultStyle()->getFont()->setItalic(true);
Leave a Reply