繁体   English   中英

从Laravel中的Excel将数据保存到db中

[英]Save data in db from excel in laravel

我需要在db中导入Excel数据。 但给我艰难的时光。 这是我的控制器功能

      $path = Input::file('import_file')->getRealPath();
        $data = \Excel::load($path)->get();

        if($data->count()){
            foreach ($data as $key => $value) {
                $arr[] = ['product_id' => $value->price, 'details' => 
                $value->stock];

            }


            if(!empty($arr)){
                \DB::table('stock')->insert($arr);
                dd('Insert Record successfully.');
            }
        }

价格和库存是excel中的字段。 下面是错误

          Property [price] does not exist on this collection instance.

当我试图将excel数据保存在db中时,这是我的控制器函数的dd()。

          SheetCollection {#375 ▼
        #title: ""
         #items: array:3 [▼
      0 => RowCollection {#498 ▼
  #heading: array:2 [▼
    0 => "stock"
    1 => "price"
  ]
  #title: "Sheet1"
  #items: array:3 [▼
    0 => CellCollection {#462 ▼
      #title: null
      #items: array:2 [▼
        "stock" => 2.0
        "price" => 3.0
      ]
    }
    1 => CellCollection {#481 ▼
      #title: null
      #items: array:2 [▼
        "stock" => 3.0
        "price" => 2.0
      ]
    }
    2 => CellCollection {#480 ▼
      #title: null
      #items: array:2 [▶]
    }
  ]
}
1 => RowCollection {#533 ▶}

我将在此处粘贴导入功能,根据需要对其进行修改。

我的excel模板只有一张纸,第一行包含字段名称。

// Retrieve file 
$file = $request->file('file'); 
$ext = $file->getClientOriginalExtension();

// Just my helper method to create filenames
$filename = Helper::create_filename($ext);

// Move file
$path ="uploads/import";
$file->move($path, $filename);

Excel::selectSheetsByIndex(0)->load("{path}/{$filename}", function($reader) { 
    $sheet = $reader->all(); 
    foreach ($sheet as $i => $row) {
        $data = $row->toArray(); // Utilize this data to fill your model
    }
});

像这样更改EXCEL SHEET栏名称

价格存量

100 400


200 15


12167

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM