Box/Spout处理excel和csv

时间:2020-09-16
本文章向大家介绍Box/Spout处理excel和csv,主要包括Box/Spout处理excel和csv使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

源地址:https://www.kancloud.cn/logoove/we7/1442125

Box/Spout处理excel和csv

 
  • 导出csv和xlsx
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$result = [];
for ($i = 0; $i < 100; $i++) {
    $arr = [
        'name' => \Mock::name(),
        'age' =>\Mock::number('10-80'),
        'email' =>\Mock::email(),
        'address' =>\Mock::address(),
        'times'=>\Mock::datetime()
    ];
    $result[] = $arr;
}
    $reader =  WriterFactory::create(Type::XLSX);
    $reader->openToBrowser("测试.xlsx");//输出到浏览器
    //$reader->openToFile(storage_path('file/s.xlsx'));//输出到文件
    $reader->addRow([
        'name'   => '姓名',
        'age'   => '年龄',
        'email'     => '邮箱',
        'address'     => '地址',
        'times'=>'时间'
    ]);
    $reader->addRows($result);
    $reader->close();
  • 读取excel的xlsx和csv
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
 $path = storage_path('file/a.xlsx');
 $type = pathinfo($path);
 $type = strtolower($type["extension"]);
 $type = ($type === 'xlsx')?Type::XLSX:Type::CSV;
 $reader = ReaderFactory::create($type);
$reader->setShouldFormatDates(true);
 if($type === 'csv'){$reader->setEncoding('GB2312');}
 $reader->open($path);
 $iterator = $reader->getSheetIterator();
 $iterator->rewind();
 $sheet1 = $iterator->current();
 $rowIter = $sheet1->getRowIterator();
 $data =[];
 foreach ($rowIter as $rowIndex => $row) {
     $data[] = $row;
 }
 $reader->close();

$flag 上一页 下一页