在laravel中 AJAX 下载maatwebsite excel

ehxuflar  于 2023-05-19  发布在  其他
关注(0)|答案(5)|浏览(136)

我想用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();
        }
    });
});

但是使用上面的控制器方法不会返回excel格式的文件,如果我将字符串值从xlsx更改为csv,那么csv的文件将被下载。
我们如何使excel格式的文件下载?任何建议,请!

rnmwe5a2

rnmwe5a21#

我知道这是相当晚,但张贴为其他人谁与我一样的问题斗争
我还需要下载Excel从使用Maatwebsite Excel库使用 AJAX 后调用。
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');

这里我使用了maatwebsite/excel库,通过FromQuery方式生成excel文件,但由于库更新,**“maatwebsite/excel”中的Excel::create已被Excel::download取代:“^3.1”**我在我的案例中使用了download方法,这里是我的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
就这些

nfs0ujit

nfs0ujit2#

只需查看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);
        }
    });
}
dm7nw8vv

dm7nw8vv3#

虽然很晚了,但要帮助别人
你可以这样做

在 AJAX 中

$(document).on('click', '#downloadExcel', function () {
        
                $("#downloadExcel").hide();
                $("#ExcelDownloadLoader").show();
            
               $.ajax({                     
                    url: '{{ route("admin.export_pending_submitted_tasks") }}',
                    method: "GET",
                    cache: false,
                    data: {
                        search_partner,
                        search_state,
                        search_city,
                        _token,
                    },
                    success: function (response) {
                      var a = document.createElement("a");
                      a.href = response.file; 
                      a.download = response.name;
                      document.body.appendChild(a);
                      a.click();
                      a.remove();
                      $("#downloadExcel").show();
                      $("#ExcelDownloadLoader").hide();
                      },
                      error: function (ajaxContext) {
                        $("#downloadExcel").show();
                        $("#ExcelDownloadLoader").hide();
                        alert('Export error: '+ajaxContext.responseText);
                      }
                }); 
        });

控制器中

// Get pending submitted tasks export excel
public function export_pending_submitted_tasks(Request $request){
    
    $input = $request->input();

    $pending_submitted_tasks = SubmittedTask::select('id', 'partner', 'se_id', 'description', 'created_at', 'status', 'updated_at');
    (isset($input['search_partner'])) ? $pending_submitted_tasks->where('partner_id', $input['search_partner']) : '';
    (isset($input['search_partner'])) ? $pending_submitted_tasks->where('state', 'like', '%'.$input['search_state'].'%') : '';
    (isset($input['search_partner'])) ? $pending_submitted_tasks->where('city', 'like', '%'.$input['search_city'].'%') : '';                
    $pendingTaskList =  $pending_submitted_tasks->where('status', 'pending')->get();
    
    if($pendingTaskList->count() > 0):
        
    $myFile =  Excel::raw(new ExportPendingTaskHelper($pendingTaskList), 'Xlsx');
    
    $response =  array(
        'name' => "Pending-Task-List.xlsx",
        'file' => "data:application/vnd.ms-excel;base64,".base64_encode($myFile)
     );
     return response()->json($response);
    
    else:
        return back()->with('message', 'No Pending tasks available to download!!');
           
    endif;
}
uurv41yg

uurv41yg4#

如果你使用jquery:
//在控制器中:

return Excel::download(new SomeExport, 'Some_Report.xlsx', null, [\Maatwebsite\Excel\Excel::XLSX]);

// AJAX :

$.ajax({
            type: 'GET',
            url: '{{ route("some.route") }}',
            data: {
                "_token": "{{ csrf_token() }}"
            },
            xhrFields:{
                responseType: 'blob'
            },
            beforeSend: function() {
                //
            },
            success: function(data) {
                var url = window.URL || window.webkitURL;
                var objectUrl = url.createObjectURL(data);
                window.open(objectUrl);
            },
            error: function(data) {
                //
            }
        });
l3zydbqr

l3zydbqr5#

// Controller


public function export()
    {
$random = rand(100000, 999999);
        $fileName = 'fresh_data_'.$random.'.xlsx';
        //  Excel::store(new FreshDataExport, $fileName);
        Excel::store(new FreshDataExport, $fileName, 'public');
        $filepath = Storage::url($fileName);
         return response()->json(['file' => $fileName, 'path' => $filepath]);
    }

相关问题