在laravel中使用ajax下载maatwebsite excel

060*_*991 2 ajax excel maatwebsite-excel laravel-5.4

我正在尝试在 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);
Run Code Online (Sandbox Code Playgroud)

阿贾克斯功能:

$(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();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,使用上述控制器方法没有返回的Excel格式的文件,如果我改变从字符串值xlsx到csv再csv格式的文件是越来越下载。

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

KAT*_*ath 8

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

我还需要使用 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>
    
    Run Code Online (Sandbox Code Playgroud)

使用以下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);
    }
});
}
Run Code Online (Sandbox Code Playgroud)

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

Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController@downloadPayroll');
Run Code Online (Sandbox Code Playgroud)

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

薪资助手.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]); 
}
}
Run Code Online (Sandbox Code Playgroud)

终于在我的控制器中

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) {

    }
}
}
Run Code Online (Sandbox Code Playgroud)

创建 excel 文件后,返回文件以获取与 blob一样的 ajax响应

就这样

  • 谢谢您的回答:)。我将尝试你的解决方案并检查 (3认同)