spatie/simple-excel 正是一款旨在简化 Excel 操作的轻量级工具。作为 Spatie 团队开发的开源项目(项目地址:https://github.com/spatie/simple-excel),它以简洁的 API 和高效的性能,成为开发者处理表格数据的得力助手。
“此软件包允许您轻松读取和写入简单的 Excel 和 CSV 文件。幕后生成器用于确保低内存使用率,即使在处理大文件时也是如此。
composer require spatie/simple-excel
假设您有一个包含此内容的 CSV
email,first_name
john@example.com,john
jane@example.com,jane
use Spatie\SimpleExcel\SimpleExcelReader;
// $rows is an instance of Illuminate\Support\LazyCollection
$rows = SimpleExcelReader::create($pathToCsv)->getRows();
$rows->each(function(array $rowProperties) {
// in the first pass $rowProperties will contain
// ['email' => 'john@example.com', 'first_name' => 'john']
});
读取 Excel 文件与读取 CSV 文件相同。只需确保提供给 SimpleExcelReader 的 create 方法的路径以 xlsx 结尾即可。
use Spatie\SimpleExcel\SimpleExcelReader;
$data = SimpleExcelReader::create('file.xlsx')->get();
foreach ($data as $row) {
// 处理每一行数据
}
如果您正在读取的文件不包含标题行,则应使用 noHeaderRow() 方法。
// $rows is an instance of Illuminate\Support\LazyCollection
$rows = SimpleExcelReader::create($pathToCsv)
->noHeaderRow()
->getRows()
->each(function(array $rowProperties) {
// in the first pass $rowProperties will contain
// [0 => 'john@example', 1 => 'john']
});
以下是编写 CSV 文件的方法
use Spatie\SimpleExcel\SimpleExcelWriter;
$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
您可以将文件直接流式传输到浏览器,而不是将文件写入磁盘。
$writer = SimpleExcelWriter::streamDownload('your-export.xlsx')
->addRow([
'first_name' => 'John',
'last_name' => 'Doe',
])
->addRow([
'first_name' => 'Jane',
'last_name' => 'Doe',
])
->toBrowser();
如果要向浏览器发送大型流,请确保调用 flush()
$writer = SimpleExcelWriter::streamDownload('your-export.xlsx');
foreach (range(1, 10_000) as $i) {
$writer->addRow([
'first_name' => 'John',
'last_name' => 'Doe',
]);
if ($i % 1000 === 0) {
flush(); // Flush the buffer every 1000 rows
}
}
$writer->toBrowser();