2017-08-11 96 views
3

我有一個導出csv函數,它與laravel一起工作良好。但現在我想通過ajax調用導出函數並使用方法後,但我沒有反應。我可以從laravel控制器發送一個變量到響應,但不能發送文件下載。使用Laravel通過Ajax導出CSV

這裏是我的代碼:

route.php

Route::get('/title/show', '[email protected]'); 
    Route::post('/title/show', '[email protected]'); 

show.blade.php

<script> 
$(document).ready(function() { 
    $('#exportFromDB').click(function() { 
     $.ajax({ 
      url: "", 
      type: "post", 
      headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, 
      data: {}, 
      success: function (response) { 
       var a = document.createElement("a"); 
       a.href = response.file; 
       a.download = response.name; 
      } 
     }) 
    }) 
}) 

TITL eController.php:

$dataExport['Oversea'] = $dataOversea; 
    $this->titleRepository->export('csv', $properties, $dataExport); 

TitleRepository.php

public function export($type, $properties, $data) 
{ 
    if (in_array($type, self::EXPORT_TYPE)) { 
     try { 
      return Excel::create($properties['_title'], function ($excel) use ($data, $properties) { 

       $excel->setTitle($properties['_title']); 
       $excel->setCreator($properties['_creator']) 
        ->setCompany($properties['_company']); 
       $excel->setDescription($properties['_description']); 

       $excel->sheet('Sheet', function ($sheet) use ($data) { 
        foreach ($data as $item) { 
         $sheet->fromArray($item); 
        } 
       }); 
      })->export($type); 
     } catch (Exception $error) { 
      throw $error; 
     } 
    } 
} 

我該如何解決這些問題?謝謝 !

回答

2

試試這個 -

  1. 不要在您的控制器方法中編寫導出代碼,而不是將excel文件保存在公用文件夾中。

  2. 你的控制器方法應該返回文件名。

  3. 在你的Ajax成功做到這一點 -

location.href =路徑/到/文件/ property_title.xls

因此,與

更換您此行

->export($type); 

->store($type, 'public/reports/', true); 
+0

這麼多,你的想法很好,但我仍然不能返回文件名。我改變 - > export()to - > store()和var_dump($ this-> titleRepository-> export('csv ',$ properties,$ dataExport))但是它返回null; 你能告訴我如何重寫我的控制器和存儲庫detailm請:( –

+0

而不是返回Excel :: create,將其賦值給變量。 ($ export){ return $ export ['full']; } else { $ message = empty($ data)?'沒有記錄('error',$ message); return redirect('client-list'); } –

+0

請a接受我的答案,如果它的工作。 –

0

我看到你的一個AJAX網址空值

將其更改爲

url : "{{ action('[email protected]') }}" 

在這之後,響應的數據,你在控制器返回

success: function (response) {} 
+0

我認爲空URL不是問題,因爲我可以通過返回(「a」)和死亡(); :( –

0

我安裝了maatwebsite/excel包,並能夠在不寫javascript的情況下完成。所有你需要做的是建立一個鏈接(或者,如果你喜歡典型形式後),像這樣的動作:

public downloadItemsExcel() { 
    $items = Item::all(); 
    Excel::create('items', function($excel) use($items) { 
     $excel->sheet('ExportFile', function($sheet) use($items) { 
      $sheet->fromArray($items); 
     }); 
    })->export('xls'); 
} 

這適用於CSV /都Excel文件。瀏覽器中沒有重新加載頁面。