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

问题描述

我正在流明中使用FastExcel将数据从excel工作表导入数据库

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

如何使用FastExcel获取工作表名称

解决方法

当前,无法获取工作表名称。 PHP库不支持它。

如果要导入特定的工作表,则没有本机的方法。您可以尝试以下一些选项。

  1. 您知道工作表编号。
$collection = (new FastExcel)->withoutHeaders()->sheet(3)->import($path);
  1. 您知道这张纸是第一张/最后一张纸。
//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);