将excel(xlsm,xls)中的数据插入laravel(cyber-duck)中

时间:2019-11-22 03:51:24

标签: php laravel cyberduck

目前,我可以从json文件中以这种格式获取excel数据

sample.xlsx

    $excel = Importer::make('Excel');
    $excel->hasHeader(true);
    $excel->load($savePath.$fileName);
    $collection = $excel->getCollection();

    if(sizeof($collection[1]) == 5)
    {
        return $collection;
    }
    else
    {
        return redirect()
        ->back()
        ->with(['errors'=> [0=> 'Please provide date in file according to your format.']])
        ->with('modal',$modal);
    }

输出

[{"id":1,"first_name":"j.doe17","last_name":"Jun Doe","email":"j.doe@gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}},{"id":2,"first_name":"j.doe18","last_name":"Jun Doe","email":"jan.doe@gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}}]

现在我正尝试使用此代码,只需将这些json数据插入我的数据库表> tbl_sampleimport

         foreach ($collection->toArray() as $key => $value)  {
            foreach ($value as $row) {
                $insert_data[] = array(
                    'first_name'  => $row['first_name'],
                    'last_name'  => $row['last_name'],
                    'email'  => $row['email'],
                    'birthdate'  => $row['birthdate'],
                    'created_at'  => now(),
                    'updated_at'  => now(),
                );

            }
        }
        DB::table('tbl_sampleimport')->insert($insert_data);

我的桌子tbl_sampleimport

enter image description here

但这给了我一个类似Illegal string offset 'first_name'

的错误

Laravel : v5.8.*

cyber-duck/laravel-excel

1 个答案:

答案 0 :(得分:1)

使用json_decode()转换为array

$arr = json_decode($collection, true);
foreach($arr as $row) {
    $insert_data[] = array(
          'first_name'  => $row['first_name'],
          'last_name'  => $row['last_name'],
          'email'  => $row['email'],
          'birthdate'  => $row['birthdate']['date'],
          'created_at'  => now(),
          'updated_at'  => now(),
     );
}