2017-08-11 98 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文件。浏览器中没有重新加载页面。