安装与入门
匿名 · 更新于 2019/12/18
本指南将帮助您安装Spout并教您如何使用它。
要求
- PHP 7.1或更高版本
ext-zip启用PHP扩展ext-xmlreader启用PHP扩展
安装
作曲家(推荐)
Spout可以直接从Composer安装。
运行以下命令:
$ composer require box/spout
手动安装
如果您不能使用Composer,请放心!您仍然可以手动安装Spout。
在开始之前,请确保您的系统符合要求。
- 从发布页面下载源代码
- 将下载的内容提取到您的项目中。
- 将此代码添加到顶部控制器(例如index.php)或更合适的位置:
// don't forget to change the path!
require_once '[PATH/TO]/src/Spout/Autoloader/autoload.php';
基本用法
读者
无论文件类型如何,读取文件的接口始终相同:
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
$reader = ReaderEntityFactory::createReaderFromFile('/path/to/file.ext');
$reader->open($filePath);
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($sheet->getRowIterator() as $row) {
// do stuff with the row
$cells = $row->getCells();
...
}
}
$reader->close();
如果文件中有多张纸,阅读器将顺序读取所有纸。
请注意,Spout根据文件扩展名猜测读取器类型。如果扩展名是不标准(.csv,.ods,.xlsx -降低/大写),特定的阅读器可被直接创建的:
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
$reader = ReaderEntityFactory::createXLSXReader();
// $reader = ReaderEntityFactory::createODSReader();
// $reader = ReaderEntityFactory::createCSVReader();
作家
与阅读器一样,有一个通用接口可将数据写入文件:
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Common\Entity\Row;
$writer = WriterEntityFactory::createXLSXWriter();
// $writer = WriterEntityFactory::createODSWriter();
// $writer = WriterEntityFactory::createCSVWriter();
$writer->openToFile($filePath); // write data to a file or to a PHP stream
//$writer->openToBrowser($fileName); // stream data directly to the browser
$cells = [
WriterEntityFactory::createCell('Carl'),
WriterEntityFactory::createCell('is'),
WriterEntityFactory::createCell('great!'),
];
/** add a row at a time */
$singleRow = WriterEntityFactory::createRow($cells);
$writer->addRow($singleRow);
/** add multiple rows at a time */
$multipleRows = [
WriterEntityFactory::createRow($cells),
WriterEntityFactory::createRow($cells),
];
$writer->addRows($multipleRows);
/** Shortcut: add a row from an array of values */
$values = ['Carl', 'is', 'great!'];
$rowFromValues = WriterEntityFactory::createRowFromArray($values);
$writer->addRow($rowFromValues);
$writer->close();
与读取器类似,如果要写入的文件的文件扩展名不是标准的,则可以通过以下方式创建特定的写入器:
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Common\Entity\Row;
$writer = WriterEntityFactory::createXLSXWriter();
// $writer = WriterEntityFactory::createODSWriter();
// $writer = WriterEntityFactory::createCSVWriter();
对于XLSX和ODS文件,每张纸的行数限制为1,048,576。默认情况下,一旦达到此限制,编写器将自动创建一个新工作表并继续向其中写入数据。
高级用法
使用Spout,您可以做更多的事情!查看完整的文档以了解所有功能。
