PhpOffice is a powerful PHP library designed for working with Microsoft Office files, especially Excel spreadsheets. This article will guide you step-by-step on how to use PhpOffice to create beautiful and functional Excel tables.
First, you need to install the PhpOffice library. Using the Composer package manager simplifies the process. Run the following command in your project directory terminal:
composer require phpoffice/phpspreadsheet
After installation, you can start using the library in your project to write Excel-related code.
Next, create a new Excel instance with the following code:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
$spreadsheet = new Spreadsheet();
This code initializes a new Excel document object, which will serve as the base for further operations.
You can retrieve the active worksheet to edit and rename it. Here is an example:
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Sheet 1');
This adds a worksheet named "Sheet 1" to the Excel document.
To make the table more attractive, you can adjust font styles and cell background colors. For example, the code below sets cell A1's font to bold, increases the font size, and applies a red background:
$sheet->getStyle('A1')->getFont()->setBold(true);
$sheet->getStyle('A1')->getFont()->setSize(14);
$sheet->getStyle('A1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FF0000');
By customizing styles, you can create tables tailored to your needs.
Adding data is straightforward. The example below inserts content into specific cells:
$sheet->setCellValue('A1', 'Beautiful Table');
$sheet->setCellValue('A2', 'First row data');
$sheet->setCellValue('B2', 'Second row data');
You can dynamically write data to different cells based on your application logic.
Finally, save the edited table as an Excel file with the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('BeautifulTable.xlsx');
This will generate a file named "BeautifulTable.xlsx" in your project directory, ready for use or download.
Using the PhpOffice library makes it easy to create and style Excel tables. This guide covers the full process from installation, worksheet creation, styling, data insertion to saving and exporting, perfect for PHP developers to get started quickly and build professional-looking Excel files. We hope this guide helps you craft attractive and functional Excel tables.