[PHP 开源类库] simple-Excel —— 兼具优雅与性能的 Excel 和 CSV 文件读写工具

PHP

https://github.com/spatie/simple-excel

该扩展包可让你轻松读取和写入简单的 Excel 和 CSV 文件。在后台使用生成器来确保低内存使用,即使在处理大型文件时也是如此。

这是有关如何读取 Excel 或 CSV 的示例。

SimpleExcelReader::create($pathToFile)->getRows()
   ->each(function(array $rowProperties) {
        // process the row
    });

如果 $ pathToFile.csv 结尾。则假定为 CSV 文件。如果以 .xlsx 结尾,则假定为 Excel 文件。

安装

你可以通过 composer 安装该软件包:

$ composer require spatie/simple-excel

用法

读取 CSV

想象你有一个包含如下内容的 CSV 文件

email,first_name
john@example.com,john
jane@example.com,jane
// $rows是 Illuminate\Support\LazyCollection 的一个实例
$rows = SimpleExcelReader::create($pathToCsv)->getRows();

$rows->each(function(array $rowProperties) {
   // 循环的第一个 $rowProperties 应该是下面这样的
   // ['email' => 'john@example', 'first_name' => 'john']
});

读取 Excel 文件

读取 Excel 文件与读取 CSV 文件相同。只需确保提供给 SimpleExcelReadercreate 方法的路径以 xlsx 结尾。

使用懒集合

getRows 将返回 LazyCollection 实例,该实例是 Laravel 框架的一部分。因为在后台使用了生成器,即使是大文件内存使用量也会较低。

你可以在这里.找到关于  LazyCollection  的方法

这是一个简单的愚蠢的例子,我们只想处理 first_name 长度大于 5 的行。

SimpleExcelReader::create($pathToCsv)->getRows()
    ->filter(function(array $rowProperties) {
       return strlen($rowProperties['first_name']) > 5
    })
    ->each(function(array $rowProperties) {
        // processing rows
    });

读取一个没有标题的文件

如果你要读取一个没有标题的文件,你应该使用 noHeaderRow()

// $rows是 Illuminate\Support\LazyCollection 的一个实例
$rows = SimpleExcelReader::create($pathToCsv)
    ->noHeaderRow()
    ->getRows()
    ->each(function(array $rowProperties) {
       // 第一次循环的 $rowProperties 会是下面这样
       // [0 => 'john@example', 1 => 'john']
});

自己创建一个阅读器

首先我们已经引入了 box/spout 这个包。 你可以通过getReader 方法获取一个阅读器的接口 \Box\Spout\Reader\ReaderInterface

$reader = SimpleExcelReader::create($pathToCsv)->getReader();

写入文件

这里将展示如何写入一个CSV文件:

$writer = SimpleExcelWriter::create($pathToCsv)
     ->addRow([
        'first_name' => 'John',
        'last_name' => 'Doe',
    ])
    ->addRow([
        'first_name' => 'Jane',
        'last_name' => 'Doe',
    ]);

pathToCsv 文件将包含以下内容:

first_name,last_name
John,Doe
Jane,Doe

写入 Excel 文件

写入 Excel 文件与写入 CSV 相同。只需确保提供给 SimpleExcelWritercreate 方法的路径以 xlsx 结尾。

将 Excel 文件流式传输到浏览器

无需将文件写入磁盘,您可以将其直接流式传输到浏览器。

$writer = SimpleExcelWriter::streamDownload('your-export.xlsx')
     ->addRow([
        'first_name' => 'John',
        'last_name' => 'Doe',
    ])
    ->addRow([
        'first_name' => 'Jane',
        'last_name' => 'Doe',
    ])
    ->toBrowser();

写入没有标题的文件

如果正在写入的文件没有标题行,则应使用 noHeaderRow() 方法。

$writer = SimpleExcelWriter::create($pathToCsv)
    ->noHeaderRow()
    ->addRow([
        'first_name' => 'Jane',
        'last_name' => 'Doe',
    ]);
});

这将输出:

Jane,Doe

添加布局

这个包底层使用了 box/spout 包。该软件包包含一个 StyleBuilder ,可用于格式化行。请注意样式只能在 Excel 文档上使用。

use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
use Box\Spout\Common\Entity\Style\Color;

$style = (new StyleBuilder())
   ->setFontBold()
   ->setFontSize(15)
   ->setFontColor(Color::BLUE)
   ->setShouldWrapText()
   ->setBackgroundColor(Color::YELLOW)
   ->build();

$writer->addRow(['values, 'of', 'the', 'row'], $style)

有关样式的更多信息,请查阅 Spout 文档.

使用替代定界符

默认情况下, SimpleExcelReader 将假定分隔符为 ,

使用其他分隔符的方法:

SimpleExcelWriter::create($pathToCsv)->useDelimiter(';');

获取写入的行数

您可以获取写入的行数。该数字包括自动添加的标题行。

$writerWithAutomaticHeader = SimpleExcelWriter::create($this->pathToCsv)
    ->addRow([
        'first_name' => 'John',
        'last_name' => 'Doe',
    ]);

$writerWithoutAutomaticHeader->getNumberOfRows() // returns 2

手动使用 writer 对象

因基于 box/spout 包,所以你可以通过 getWriter 来获取到底层的 \Box\Spout\Reader\WriterInterface 实现:

$writer = SimpleExcelWriter::create($pathToCsv)->getWriter();
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://github.com/spatie/simple-excel

译文地址:https://learnku.com/php/t/41360

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
讨论数量: 2

和xlswriter性能有对比吗

4年前 评论
Summer

@jsoner 这个底层用了 https://github.com/box/spout ,虽然比 Laravel Excel 速度要快,但是比 xlswriter 速度还不是一个档次的。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!