Spout is an alternative to PHPExcel library. I was a big fan of PHPEXcel, but later I find out that this library consumes huge amount of memory. In my case, I often work with large data sets, so this started
making problem for me. After researching a lot in Google, I just find out this cool piece of code.
This guide will help you install Spout and teach you how to use it.
Requirements
In order to work with spout you need to have below things installed in your server
- PHP version 5.4.0 or higher
- PHP extension php_zip enabled
- PHP extension php_xmlreader enabled
Installation
Composer way
Run the follwoing composer command in your shell
composer require box/spout
How to install Spout manually.
Download the source code from the Releases page https://github.com/box/spout/releases
Extract the downloaded content into your project.
Add this code to the top controller (e.g. index.php) or wherever it may be more appropriate:
Call the autoloader file to your php file
// don't forget to change the path! require_once '[PATH/TO]/vendor/autoload.php';
Reading an excel using spout
require_once 'vendor/box/spout/src/Spout/Autoloader/autoload.php'; use Box\Spout\Reader\ReaderFactory; use Box\Spout\Common\Type; $reader = ReaderFactory::create(Type::XLSX); // for XLSX files //$reader = ReaderFactory::create(Type::CSV); // for CSV files //$reader = ReaderFactory::create(Type::ODS); // for ODS files $filePath ='file.xlsx'; $reader->open($filePath); foreach ($reader->getSheetIterator() as $sheet) { foreach ($sheet->getRowIterator() as $row) { print_r($row); } } $reader->close();
Writing a excel file using spout
require_once '[PATH/TO]/vendor/autoload.php'; use Box\Spout\Writer\WriterFactory; use Box\Spout\Common\Type; $writer = WriterFactory::create(Type::XLSX); // for XLSX files //$writer = WriterFactory::create(Type::CSV); // for CSV files //$writer = WriterFactory::create(Type::ODS); // for ODS files $writer->openToFile('file.xlsx'); // write data to a file or to a PHP stream //$writer->openToBrowser($fileName); // stream data directly to the browser $writer->addRow(array('sku','price')); // add a row at a time $writer->addRow(array('90989812209','299.00')); // add a row at a time $writer->addRows(array(0=>array('sku','price'),2=>array('090909345789','200'))); // add multiple rows at a time $writer->close();
For XLSX and ODS files, deafult number of rows per sheet is limited to 1,048,576. After that spout will create a new tab inside your sheet will write to your excel.
Hi, I desire to subscribe for this blog to take latest updates,
so where can i do it please help out.
It’s added to the right hand side of the website