如何导入Excel文件并将数据添加到数据库中?我在控制器中有逻辑(我认为),但是我不确定如何从Vue将其发送到控制器?我将此代码基于我正在从事的另一个项目和教程中,但我不知道如何使它适应我的项目。
这是控制器存储功能
public function store(Request $request)
{
ini_set('max_execution_time', 300);
$users = $request->all();
try {
DB::beginTransaction();
foreach ($users as $user) {
$dbUser = $this->getUser($user['CARNET']);
Log::error($dbUser);
$dbUser->name = $user['NOMBRE'];
$dbUser->card = $user['CEDULA'];
$dbUser->scard = $user['CARNET'];
$dbUser->email = $user['CORREO'];
$dbUser->password = $user['PASSWORD'];
$this->isSet('TIPO-USUARIO', $user);
$user_type_id = $this->getUserId($user['TIPO-USUARIO']);
$dbUser->user_type_id = $user_type_id->id;
$dbUser->save();
foreach (explode(',', str_replace(' ', '', $user['CATEGORIA-USUARIO'])) as $c) {
$category = $this->getCategory($c);
$dbUser->userCategory()->save($category);
}
$dbUser->save();
}
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new HttpException(500, 'Sucedio un error importando la información favor intentar de nuevo');
}
}
我的想法中有什么
<input type="file" name="file" class="inputfile" id="fileUpload"/>
<label for="fileUpload">Select Excel</label>
<el-button
style="margin: 5px; margin-left: 20px"
type="primary"
class="mt-1"
:loading="loading"
@click="sendData()">Import
</el-button>
sendData(data) {
this.loading = true;
this.error = {};
this.$http.post(this.baseUrl, data, this.params)
.then(
() => {
this.successAction();
this.errorDis = false;
},
(res) => {
this.showErrors(res);
this.errorDis = true;
}
);
},
successAction() {
this.loading = false
},
showErrors(res) {
const [message, errors] = parseError(res);
this.error = {
message,
errors
};
this.loading = false;
this.processing = false;
},
我不确定如何将实际数据发送到控制器以进行保存。
您可以使用Laravel-Excel来读取文件,创建对象或数组并将数据存储在所需的表上。在视图(刀片,vue,jqueery等)中,您只需要通过这样的路由将文件作为POST发送:
Route::post('/importExcel', 'YourController@importExcelmethod');