Create an xlsx file and change the default cell white background color to a different one.
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 !'); // Apply a solid type background to 'A1' $sheet->getStyle('A1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID); // Fill up the background of 'A1' with color blue $sheet->getStyle('A1')->getFill()->getStartColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLUE); // Set cell A2 with the "Hello World !" string value $sheet->setCellValue('A2', 'Hello World !'); // Apply a solid type background to 'A2' $sheet->getStyle('A2')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID); // Fill up the background of 'A2' with color red $sheet->getStyle('A2')->getFill()->getStartColor()->setARGB('FFFF0000'); // Write a new .xlsx file $writer = new Xlsx($spreadsheet); // Save the new .xlsx file $writer->save('create-xlsx-files-with-different-cell-background-colors.xlsx');
Test.
Run the following codes.
$ php create-xlsx-files-with-different-cell-background-colors.php
Result.
Open the generated file create-xlsx-files-with-different-cell-background-colors.xlsx.
