导出功能:
maatwebsite/excel 使用此组件用作导出,效果比较友好,但是感觉导入就不太友好
导入:
box/spout 推荐使用这个组件 导入效果比较好-- https://opensource.box.com/spout/getting-started/#reader
生成一个导入类 在控制器中 获取上传文件request()->file('file'); Import::import($filePath); 返回的则是表格内数据
<?php
namespace App\Import;
use Box\Spout\Reader\Common\Creator\ReaderFactory;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
class Import
{
public static function import($files)
{
$data = [];
// 获取上传文件名称
// $filename = $files->getClientOriginalName();
$ext = $files->getClientOriginalExtension();
if (!in_array($ext, ['csv', 'xlsx'])) {
throw new \Exception('表格类型错误,暂时只支持csv,xlsx', 400);
}
/** @var \Box\Spout\Reader\ReaderAbstract */
$reader = ReaderFactory::createFromType($ext);
$reader->setShouldFormatDates(true);
if ($ext === 'csv') {
/** @var \Box\Spout\Reader\CSV\Reader $reader */
$reader->setEncoding('GB2312');
}
$reader->open($files);
$iterator = $reader->getSheetIterator();
$iterator->rewind();
/**
* 只能获取第一页数据
* @var \Box\Spout\Reader\XLSX\Sheet
*/
$sheet1 = $iterator->current();
$rowIter = $sheet1->getRowIterator();
foreach ($rowIter as $rowIndex => $row) {
$rowArr = $row->toArray();
$data[] = array_splice($rowArr, 0, 64);
}
$reader->close();
return collect($data);
}
}
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory
$ext = $files->getClientOriginalExtension();
switch ($ext) {
case 'csv':
$reader = ReaderEntityFactory::createCSVReader();
break;
case 'xlsx':
$reader = ReaderEntityFactory::createXLSXReader();
break;
}
$reader->open($files);
$iterator = $reader->getSheetIterator();
foreach ($iterator as $sheet) {
foreach ($sheet->getRowIterator() as $rowIndex => $row) {
$rowArr = $row->toArray();
if (!is_null($skpStep)) {
if ($rowIndex == $skpStep) {
continue;
}
}
$data[] = array_splice($rowArr, 0, 64);
}
}
$reader->close();