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();

相关文章:

  • 2022-12-23
  • 2021-10-26
  • 2021-07-31
  • 2022-12-23
  • 2021-04-10
  • 2021-11-19
  • 2022-12-23
猜你喜欢
  • 2021-09-17
  • 2021-10-02
  • 2021-07-25
  • 2021-12-08
  • 2022-12-23
  • 2022-12-23
  • 2021-07-28
相关资源
相似解决方案