【问题标题】:Import an excel and insert into database导入excel并插入数据库
【发布时间】:2020-02-24 02:28:46
【问题描述】:

如何导入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');
    }
}

我的 vue 中有什么

<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 vue.js element-ui


    【解决方案1】:

    您可以使用Laravel-Excel 来读取文件、创建对象或数组并将数据存储在您想要的表中。在视图(blade、vue、jQuery 等)中,您只需通过如下路径将文件作为 POST 发送:

    Route::post('/importExcel', 'YourController@importExcelmethod');
    

    在控制器中你可以做这样的事情:

    public function importExcel(Request $request)
    {
        if($request->file('import_file')){
            $path = $request->file('import_file')->getRealPath();
            $data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
            })->get()->toArray();
            if(!empty($data) && (count($data)> 0)){
                foreach ($data as $key => $value) {
                    DB::table('your_table')->insert(
                        [
                            "a_column" => $value[0],
                            "another_comun" => $value[1],
                            //etc
                        ]
                    );
                }
    

    更多信息和例子在这里:https://docs.laravel-excel.com/3.1/imports/

    实际上有一些更简单的例子来说明如何将数据从 xls 存储到模型中,如下所示:

    public function import() 
    {
        Excel::import(new UsersImport, 'users.xlsx');
    
        return redirect('/')->with('success', 'All good!');
    }
    

    【讨论】:

    • 我安装了它,但又不知道如何使用它
    • 好吧,你可以这么说。然后我将编辑我的答案,等待
    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多