使用Vue和Laravel导入Excel

时间:2019-03-01 08:06:35

标签: javascript php excel laravel vue.js

您可以帮助我将excel导入到我的程序中吗?我使用maatwebsite/excel上传Excel文件。

所以,我有

BarangController.php

public function import(Request $request)
{
    // $path = $request->file('excel')->getRealPath();
    $data = Excel::load($request->file('excel'))->get();

     if($data->count()){
        foreach ($data as $key => $value) {
            $arr[] = ['nama_barang' => $value->nama_barang];
        }

        if(!empty($arr)){
            return $arr;
        }
    }
}

Index.vue(模态)

              <!-- Modal body -->
              <div class="modal-body">
                <div class="input-group">
                  <input @change="uploadExcel" id="excel" type="file" class="custom-file-input">
                  <label class="custom-file-label" for="excel">{{ fileName }}</label>
                </div>
              </div>
              <!-- Modal footer -->
              <div class="modal-footer">
                <button @click="importExcel" type="button" class="btn btn-primary float-left">Import</button>
                <button type="button" class="btn btn-danger float-right" data-dismiss="modal">Batal</button>
              </div>

Index.vue(方法js)

importExcel() {
      this.$Progress.start();
      this.import.post('/api/barang/import').then((data) => {
        console.log(data.data);
        this.$Progress.finish();
      }).catch(() => {
        this.$Progress.fail();
      })
    },
    uploadExcel(e) {
      let file = e.target.files[0];
      let reader = new FileReader();

      // console.log(file);
      if(file['type'] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
        this.fileName = file['name'];
        //this.import.excel = file;
        reader.onloadend = (file) => {
          this.import.excel = reader.result;
        }
        reader.readAsDataURL(file);
        //this.import.excel = file;
        console.log(this.import.excel);
      } else {
        Swal.fire({
          type: 'warning',
          title: 'Format file salah'
        })
      }
    },

当我在控制台日志中查看时,它无法获得excel的数组结果,希望您能为我提供帮助,谢谢

2 个答案:

答案 0 :(得分:0)

如果您直接return $data = Excel::load($request->file('excel'))->get();直接使用控制器的导入方法怎么办?控制台会说什么?

答案 1 :(得分:0)

首先,您必须通过上传功能传递$ event。就像@ change = uploadExcel($ event)。然后尝试使用此功能。

         uploadExcel(e){

                let file = e.target.files[0];
                var reader = new FileReader()
                reader.readAsText(file)
                this.fileName = file['name']

                reader.onloadend = (event) => {
                     this.result = event.target.result;
                     console.log("test", this.result)   
                }   
            }