You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Excel动态工作表处理:动态表名导入与表名获取

Laravel Excel 处理动态表名多表导入及获取工作表名称

获取所有工作表名称

你可以通过两种方式获取Excel文件的所有工作表名称:

方式1:使用Laravel Excel Facade

use Maatwebsite\Excel\Facades\Excel;

$filePath = storage_path('app/your-excel-file.xlsx');
$sheetNames = Excel::getSheetNames($filePath);
// $sheetNames 为包含所有表名的数组

方式2:直接调用PhpSpreadsheet底层方法

use PhpOffice\PhpSpreadsheet\IOFactory;

$filePath = storage_path('app/your-excel-file.xlsx');
$reader = IOFactory::createReaderForFile($filePath);
$sheetNames = $reader->listWorksheetNames($filePath);

处理动态表名的多表导入

通过实现WithMultipleSheets接口并结合ConditionalSheets特性,你可以根据表名规则动态绑定对应的导入类:

1. 创建主导入类

use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\ConditionalSheets;

class DynamicMultiSheetImport implements WithMultipleSheets
{
    use ConditionalSheets;

    public function __construct()
    {
        // 绑定固定表名的导入类
        $this->addSheet('topsheet', new TopSheetImport());

        // 匹配以rccsheet_开头的动态表名
        $this->addConditionalSheet(function(string $sheetName) {
            return str_starts_with($sheetName, 'rccsheet_');
        }, new RCCSheetImport());

        // 匹配以finishing_开头的动态表名
        $this->addConditionalSheet(function(string $sheetName) {
            return str_starts_with($sheetName, 'finishing_');
        }, new FinishingImport());
    }
}

2. 编写对应子导入类

每个子导入类需实现Laravel Excel的导入接口(如ToModel或ToCollection),示例如下:

use Maatwebsite\Excel\Concerns\ToModel;

class TopSheetImport implements ToModel
{
    public function model(array $row)
    {
        // 处理topsheet的行数据,返回模型或自定义逻辑
        return new YourModel([
            'column1' => $row[0],
            'column2' => $row[1],
            // 其他字段映射
        ]);
    }
}

RCCSheetImport和FinishingImport类同理,根据各自表的结构实现数据处理逻辑即可。

3. 执行导入

use Maatwebsite\Excel\Facades\Excel;

Excel::import(new DynamicMultiSheetImport(), $filePath);

进阶:正则匹配表名

如果需要更复杂的表名匹配规则,可使用正则表达式:

$this->addConditionalSheet(function(string $sheetName) {
    // 匹配rccsheet_后跟随任意字符的表名
    return preg_match('/^rccsheet_.+$/', $sheetName);
}, new RCCSheetImport());

内容的提问来源于stack exchange,提问作者Pranav Mankar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:22:43