我想通过Excel文件将一些数据导入数据库。但上传Noting时会上传到数据库中。
我不确定这里有什么问题,如果有人发现,希望帮助我找到它。
这是我的控制器:
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader){})->get()->toArray();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($insert)){
DB::table('items')->insert($insert);
// dd('Insert Record successfully.');
}
}
}
return back();
}
这是刀片视图:
<html lang="en">
<head>
<title>Import - Export Laravel 5</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Import - Export in Excel and CSV Laravel 5</a>
</div>
</div>
</nav>
<div class="container">
<a href="{{ URL::to('downloadExcel/xls') }}"><button class="btn btn-success">Download Excel xls</button></a>
<a href="{{ URL::to('downloadExcel/xlsx') }}"><button class="btn btn-success">Download Excel xlsx</button></a>
<a href="{{ URL::to('downloadExcel/csv') }}"><button class="btn btn-success">Download CSV</button></a>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" >
<input type="file" name="import_file" />
{!! Form::token(); !!}
{!! csrf_field() ; !!}
<button class="btn btn-primary">Import File</button>
</form>
</div>
</body>
</html>
答案 0 :(得分:1)
请使用: 使用Maatwebsite \ Excel \ Facades \ Excel;
并确保excel列标题的名称与数据库字段名称完全相同:
public function importExcelDemo(Request $request)
{
$rules = array(
'import_file' => 'required'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails())
{
return Redirect::to('/home')->withErrors($validator);
}
else
{
try
{
Excel::load('C:/Users/EBIZ43/Downloads/'. $request['import_file'], function ($reader)
{
foreach ($reader->toArray() as $row)
{
$data = $this->ads_repo->prepareData($row);
$result = $this->ads_repo->create($data);
}
});
\Session::flash('success', 'Data imported successfully.');
return redirect('/home');
}
catch (\Exception $e)
{
\Session::flash('error', $e->getMessage());
return redirect('/home');
}
}
}
答案 1 :(得分:1)
我认为缺少的是这个enctype =&#34; multipart / form-data&#34;在你的形式。希望它有所帮助
答案 2 :(得分:0)
一般情况下,当您使用过时的外墙时,我看到您在Laravel 5上标记了问题。
我建议您对代码进行以下更新:
public function importExcel(Request $request)
{
$file = $request->file('import_file')
if($file){
$path = $file->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($insert)){
DB::table('items')->insert($insert);
// dd('Insert Record successfully.');
}
}
}
}
我想说,您已经安装了Excel库。