Working with CSV in PHP: PhpSpreadsheet Library

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is PhpSpreadsheet and why is it needed?

PhpSpreadsheet is a powerful PHP library for working with spreadsheets. It allows you to read, write, and edit files in CSV, XLS, XLSX, ODS, and other formats. Unlike built-in PHP functions (e.g., fgetcsv), PhpSpreadsheet offers an object-oriented approach, automatic encoding handling, support for styles, formulas, and large data volumes. The library is ideal for importing/exporting data from web forms, generating reports, migrating between databases, and integrating with Excel/Google Sheets.

Installation

Installation is done via Composer:

composer require phpoffice/phpspreadsheet

After installation, include the autoloader:

require 'vendor/autoload.php';

Main Features

  • Reading CSV — loading a file into a Spreadsheet object with automatic delimiter detection.
  • Writing CSV — creating and saving a file with configurable delimiter, enclosure, and BOM.
  • Working with sheets — creating, deleting, renaming, and copying sheets.
  • Formatting — cell styles (fonts, colors, borders, alignment).
  • Formulas and functions — support for SUM, AVERAGE, IF, and others.
  • Handling large data — streaming writing via Xlsx Writer to reduce memory consumption.

Code example: reading and writing CSV

Reading a CSV file and outputting data:

use PhpOffice\\PhpSpreadsheet\\IOFactory;

$inputFileName = './data.csv';$spreadsheet = IOFactory::load($inputFileName);$worksheet = $spreadsheet->getActiveSheet();$data = $worksheet->toArray();

foreach ($data as $row) { echo implode(', ', $row) . "";}

Writing data to CSV:

use PhpOffice\\PhpSpreadsheet\\Spreadsheet;use PhpOffice\\PhpSpreadsheet\\Writer\\Csv;

$spreadsheet = new Spreadsheet();$sheet = $spreadsheet->getActiveSheet();

$sheet->setCellValue('A1', 'Name');$sheet->setCellValue('B1', 'Email');$sheet->setCellValue('A2', 'Ivan');$sheet->setCellValue('B2', 'ivan@example.com');

$writer = new Csv($spreadsheet);$writer->setDelimiter(';');$writer->setEnclosure('"');$writer->save('./output.csv');

When to use

PhpSpreadsheet is recommended in the following cases:

  • Support for multiple formats (CSV, XLSX, ODS) in one project is required.
  • Precise formatting (colors, fonts, cell merging) is needed.
  • You need to work with formulas or large datasets (more than 10,000 rows).
  • You prefer an OOP style and do not want to write low-level parsers.

For simple tasks (e.g., reading a single CSV with a known structure), built-in PHP functions may suffice. But if the project grows and requires flexibility, PhpSpreadsheet will become an indispensable tool.

Recommendations