将Excel文件上传到数据库时如何解决“非法字符串偏移”

时间:2019-12-04 10:54:44

标签: php laravel

我正在尝试使用 MaatWebsite包将Excel文件导入到我的表中。但是每次我遇到这样的错误:

  

非法字符串偏移量'Emp'

我正在关注此tutorial。这是我尝试过的代码:

 $path = $request->file('attendance_data')->getRealPath();

 $data = Excel::load($path)->get();

 if($data->count() > 0)
 {
     foreach($data->toArray() as $key => $value)
     {
         foreach($value as $row)
         {
             $insert_data[] = array(
                 'employee_card'  => $row['Emp'],
                 'attendance_date'   => $row['Date'],
                 'attendance_time'    => $row['On'],
             );
         }
     }

     if(!empty($insert_data))
     {
         DB::table('attendance_logs')->insert($insert_data);
     }

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

我无法发表评论,因此已将其发布为答案。

您是否尝试过死掉$row并转储以检查它是否是key => value对的数组?尝试使用数字键访问数组的键时,似乎会显示该错误。如果$row是字符串,也会发生这种情况,因为您可以使用类似于数组的数字索引来访问字符串字符。

$path = $request->file('attendance_data')->getRealPath();

$data = Excel::load($path)->get();

if($data->count() > 0) {

  foreach ($data->toArray() as $key => $value) {

    foreach ($value as $row) {

      // Print the data of $row to see what it actually is
      // and kill the process
      dd($row);

      $insert_data[] = array(
        'employee_card' => $row['Emp'],
        'attendance_date' => $row['Date'],
        'attendance_time' => $row['On'],
      );

    }

  }

  if (!empty($insert_data)) {

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

  }

}

This answer似乎相关。