代码之家  ›  专栏  ›  技术社区  ›  Zong

Laravel如何将EXCEL文件上载到数据库?

  •  0
  • Zong  · 技术社区  · 8 年前

    我的Laravel版本是5.6。PHP是7。 我在网上找到了一些上传示例,但大多数都不起作用。 有没有人能给我提供一个完整的例子? 我在网上发现了一个类似的案例。 Laravel 5.6 Excel and CSV import export using maatwebsite example

    不幸的是,它也不起作用。

    这是我的源代码。 刀身php

    <form class="form-upload" method="POST" action="{{url('/excelUpload')}}" enctype="multipart/form-data">
                {{ csrf_field() }}
                 <div class="form-group">
                    <label for="file">excel upload</label>
                    <input type="file" id="file" name="ex_file">
                    <p class="help-block">!!!</p>
                 </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default">cancel</button>
                    <button type="submit" class="btn btn-primary" id="upload_f">submit</button>
    

    控制器。php

    public function excelUpload(Request $request){
    
             if($request->hasFile('StudentUploadSample')){
                 return "yes i have a file";
             }
             return "nofile";
        }
    

    然而,结果总是显示“ 无文件 “。 我没有使用任何“ 使用 “.我应该用点什么吗? 网页上的示例未使用任何“ 使用 “”也是。 此外,我阅读了一些网站,这些文件将放在存储文件夹下,但我在存储文件夹中找不到我的文件“StudentUploadSample.xlsx”。

    有没有人能给我提供一个完整的例子或者如何解决这个问题?

    4 回复  |  直到 8 年前
        1
  •  3
  •   dekts    8 年前

    替换文件名并使用参考网站,在那里您将获得正确的代码并进行解释。

    参考站点,如: http://www.expertphp.in/article/laravel-5-maatwebsite-import-excel-into-db-and-export-data-into-csv-and-excel

    public function importFileIntoDB(Request $request){
        if($request->hasFile('sample_file')){
            $path = $request->file('sample_file')->getRealPath();
            $data = \Excel::load($path)->get();
            if($data->count()){
                foreach ($data as $key => $value) {
                    $arr[] = ['name' => $value->name, 'details' => $value->details];
                }
                if(!empty($arr)){
                    \DB::table('products')->insert($arr);
                    dd('Insert Record successfully.');
                }
            }
        }
        dd('Request data does not have any files to import.');      
    } 
        2
  •  1
  •   Pavel    8 年前

    您在控制器中使用了错误的文件名:

    if($request->hasFile('ex_file')){
         return "yes i have a file";
      }
    

    所以,修复它,并尝试检查。

        3
  •  0
  •   Chirag Patel    8 年前

    代替 <input type="file" id="file" name="ex_file"> 具有 <input type="file" id="file" name="StudentUploadSample">

    你就完了。

        4
  •  0
  •   shubiao-yao    8 年前

    您可以使用laravel excel。

    地址: https://github.com/Maatwebsite/Laravel-Excel

    /** *我的控制器代码 * */

    $更新文件=$请求->文件(“update\u file”);

    $fileSize=(int)fileSize($updateFile);

    $文件扩展=$更新文件->getClientOriginalExtension();

    $文件路径=$更新文件->getRealPath();

    $excelData=Excel::加载($filePath)->get()->toArray();

    或者您可以使用: https://phpspreadsheet.readthedocs.io/en/develop/