如何在 Laravel 中使用 Fastexcel 获取工作表名称

How to get worksheet name using Fastexcel in Laravel

我在 Lumen 中使用 FastExcel 将数据从 excel sheet 导入数据库。

$collection = (new FastExcel)->withoutHeaders()->import($path);

如何使用 FastExcel 获取作品sheet名称?

目前无法获取 sheet 姓名。 PHP 库不支持它。

如果您想导入特定的 sheet,没有本地方法可以做到这一点。您可以尝试下面的一些选项。

  1. 你知道 sheet 号码。
$collection = (new FastExcel)->withoutHeaders()->sheet(3)->import($path);
  1. 你知道 sheet 是 first/last sheet。
//last one
$collection = (new FastExcel)->withoutHeaders()->importSheets($path)->last();
// or first one
$collection = (new FastExcel)->withoutHeaders()->importSheets($path)->first();
  1. 如果你真的想用一个特定的名字导入。据我所知,你必须使用另一个库 Box/Spout 来帮助你。

注意:下面的代码很旧,我不确定它是否对当前版本仍然有效,但逻辑是正确的。可以修改代码调整最新版本

    use Rap2hpoutre\FastExcel\FastExcel;
    use Box\Spout\Reader\ReaderFactory;
    use Box\Spout\Common\Type;
    
    $sheetNames = [];

    $reader = ReaderFactory::create(Type::XLSX);

    $reader->open($path);

    foreach($reader->getSheetIterator() as $sheet)  {
        if($sheet->getName() == 'TheOneIWant'){
            array_push($sheetNames,$sheet->getName());
        }
    }

    $sheets = (new FastExcel)->importSheets($path);

我们可以使用 withSheetsNames。 请检查参考 https://github.com/rap2hpoutre/fast-excel#import-multiple-sheets