【问题标题】:Download maatwebsite excel using ajax in laravel在 laravel 中使用 ajax 下载 maatwebsite excel
【发布时间】:2018-02-28 02:58:22
【问题描述】:

我正在尝试在 laravel 中使用 ajax 方法下载一个 excel 文件。 控制器功能:

$myFile = Excel::create($name, function ($excel) use ($export) {
            $excel->sheet('Data', function ($sheet) use ($export) {
                $sheet->fromArray($export);

                $sheet->cells('A1:N1', function ($cells) {

                    $cells->setBackground('#dbdbdb');
                    $cells->setFontColor('#000000');
                    $cells->setFontWeight('bold');
                    $cells->setFont(array(
                        'family' => 'Calibri',
                        'size'   => '9',

                    ));

                });

                $sheet->setStyle(array(
                    'font' => array(
                        'name' => 'Calibri',
                        'size' => 9,

                    ),
                ));

            });
        });
        $myFile   = $myFile->string('xlsx'); 
        $response = array(
            'name' => $name, 
            'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($myFile), 
        );

        return response()->json($response);

Ajax 函数:

$(document).on('click', '.ExportJobs', function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var ids = [];
    $(".InvoiceCheckBox:checked").each(function(e) {
        ids.push(this.value);
    });
    data = {
        "ids": ids,
    };
    $.ajax({
        method: "POST",
        url: "/exportNew",
        data: data,
        success: function(response) {
            var a = document.createElement("a");
            a.href = response.file;
            a.download = response.name;
            document.body.appendChild(a);
            a.click();
            a.remove();
        }
    });
});

但是,如果我将字符串值从xlsx 更改为csv 然后csv 格式文件正在下载,则使用上述控制器方法不会返回excel 格式文件。

我们如何使excel格式的文件下载?任何建议,请!

【问题讨论】:

    标签: ajax excel laravel-5.4 maatwebsite-excel


    【解决方案1】:

    只需查看xhrFields 将responseType 设置为blob,然后查看ajax 成功部分。希望大家找到解决办法:

    <script>
    $(document).ready(function(){
        $("#ExportData").click(function()
        {
            dataCaptureExport();
        });
    });
    
    function dataCaptureExport(){
    
        var FromDate = $('#dateFrom').val();
        var ToDate = $('#dateTo').val();
        var dataString = { FromDate: FromDate, ToDate:ToDate, _token: '{{csrf_token()}}'};
    
        $.ajax
        ({
            type: "POST",
            url: '{{ route('invoice_details_export') }}',
            data: dataString,
            cache: false,
            xhrFields:{
                responseType: 'blob'
            },
            success: function(data)
            {
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(data);
                link.download = `Invoice_details_report.xlsx`;
                link.click();
            },
            fail: function(data) {
                alert('Not downloaded');
                //console.log('fail',  data);
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      我知道这已经很晚了,但是为像我一样遇到同样问题的其他人发帖

      我还需要通过使用 ajax post call 从 Maatwebsite excel 库中下载 excel。

      1. 添加了一个按钮来触发 ajax 调用以下载 excel 文件

         <button onclick="downloadExcel()" id="btn-download-payroll" class="btn btn-dark-success btn-md" style="transform: translateY(50%); top: 50%; font-size: 13px;"><i aria-hidden="true" class="fa fa-cog mr-10"></i>
                                Download
                            </button>
        

      使用以下js代码发布ajax请求

      function downloadExcel() {
      var salaryMonth = $("#dp-salary-month").datepicker("getDate");
      var department = $("#cbox-department");
      var month = new Date(salaryMonth).getMonth() + 1;
      var year = new Date(salaryMonth).getFullYear();
      $.ajax({
          xhrFields: {
              responseType: 'blob',
          },
          type: 'POST',
          url: '/downloadPayroll',
          data: {
              salaryMonth: month,
              salaryYear: year,
              is_employee_salary: 1,
              department: department.val()
          },
          success: function(result, status, xhr) {
      
              var disposition = xhr.getResponseHeader('content-disposition');
              var matches = /"([^"]*)"/.exec(disposition);
              var filename = (matches != null && matches[1] ? matches[1] : 'salary.xlsx');
      
              // The actual download
              var blob = new Blob([result], {
                  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
              });
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(blob);
              link.download = filename;
      
              document.body.appendChild(link);
      
              link.click();
              document.body.removeChild(link);
          }
      });
      }
      

      routes/web.php 文件中为我的控制器设置路由

      Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController@downloadPayroll');
      

      这里我使用 ma​​atwebsite/excel 库通过 FromQuery 方法生成 excel 文件,但由于库更新 Excel::create 已被替换为 Excel::download 在 "maatwebsite/excel": "^3.1" 在我的案例中我使用了下载方法,这里是我的 HelperClass 根据我的要求生成记录

      PayrollHelper.php

      namespace App\Http\Helpers;
      
      use App\PayrollEmployee;
      use Maatwebsite\Excel\Concerns\FromQuery;
      use Maatwebsite\Excel\Concerns\Exportable;
      
      class PayrollHelper implements FromQuery
      {
      use Exportable;
      
      public function forDepartment(int $department)
      {
          $this->department = $department;
          return $this;
      }
      
      public function forMonth(string $month)
      {
          $this->month = $month;
          return $this;
      }
      
      public function query()
      {
      // get the salary information for the given month and given department 
          return PayrollEmployee::query()->where(['salary_month' => $this->month,'department_id'=>$this->department]); 
      }
      }
      

      终于在我的控制器中

      class PayrollController extends Controller
      {
      public function downloadPayroll(Request $request)
      {
          $file_name = '';
      
      
          try {
              $requestData = $request->all();
              $salary_month = $requestData['salaryMonth'];
              $salary_year = $requestData['salaryYear'];
              $department = $requestData['department'];
              $is_employee_salary = boolval($requestData['is_employee_salary']);
              $month = Carbon::createFromDate($salary_year, $salary_month);
              $month_start = Carbon::parse($month)->startOfMonth();
              $formated_month = Carbon::parse($month)->format('F Y');
              $file_name = 'Employee_salary_' . $formated_month . '.xlsx';
      
              // to download directly need to return file
              return Excel::download((new PayrollHelper)->forMonth($month_start)->forDepartment($department), $file_name, null, [\Maatwebsite\Excel\Excel::XLSX]);
      
      
          } catch (exception $e) {
      
          }
      }
      }
      

      创建excel文件后返回文件获取为ajax响应为blob

      就是这样

      【讨论】:

      • 谢谢你的回答:)。我会尝试你的解决方案并检查
      猜你喜欢
      • 2023-03-27
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2021-10-08
      • 2016-07-15
      • 1970-01-01
      • 2021-09-17
      相关资源
      最近更新 更多