Current Location: Home> Latest Articles> PHPExcel Library Tutorial: Easily Create and Manage Excel Files

PHPExcel Library Tutorial: Easily Create and Manage Excel Files

gitbox 2025-07-18

Introduction

PHPExcel is a powerful PHP library designed for handling Excel files. It offers a rich set of interfaces that allow developers to read, write, and format Excel data easily, greatly improving the efficiency of Excel file processing.

Installing PHPExcel

Before using PHPExcel, you need to download and install the package. You can get the latest version from the official PHPExcel source, then unzip the library files into your project directory.

Include the PHPExcel library in your PHP code like this:

<span class="fun">require_once 'PHPExcel/Classes/PHPExcel.php';</span>

Creating an Excel File

You can create a new Excel document by instantiating the PHPExcel class:

<span class="fun">$excel = new PHPExcel();</span>

Adding Data

Use the setCellValue method to insert data into specific cells:

$excel->getActiveSheet()->setCellValue('A1', 'Name');
$excel->getActiveSheet()->setCellValue('B1', 'Age');
$excel->getActiveSheet()->setCellValue('A2', 'John');
$excel->getActiveSheet()->setCellValue('B2', 20);

Styling Cells

PHPExcel allows you to set font colors, background fills, and borders to enhance the appearance of your Excel file. For example:

$excel->getActiveSheet()->getStyle('A1')->getFont()->setColor(new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_RED));
$excel->getActiveSheet()->getStyle('A1:B2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FFFF00');
$excel->getActiveSheet()->getStyle('A1:B2')->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

Reading Excel Files

To read an existing Excel file, use the load method from PHPExcel_IOFactory:

<span class="fun">$excel = PHPExcel_IOFactory::load('example.xlsx');</span>

Reading Cell Data

Retrieve the content of a specific cell with the getCell method:

<span class="fun">$data = $excel->getActiveSheet()->getCell('A1')->getValue();</span>

Iterating Through Excel Files

You can loop through all rows and cells in the Excel sheet to process each cell’s data:

foreach ($excel->getActiveSheet()->getRowIterator() as $row) {
    foreach ($row->getCellIterator() as $cell) {
        $data = $cell->getValue();
        // Process data
    }
}

Saving Excel Files

After making changes, save the file using createWriter method from PHPExcel_IOFactory:

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$writer->save('output.xlsx');

Conclusion

PHPExcel offers PHP developers an easy and efficient way to handle Excel files, supporting creation, writing, styling, reading, and saving. Mastering these basic operations will help you improve your Excel file processing capabilities and meet various project requirements.