簡體   English   中英

Laravel phpspreadsheet 使用 ajax 傳遞數據

[英]Laravel phpspreadsheet passing data with ajax

我打算使用 phpspreadsheet 直接從數據庫中提取我們的費用。 我仍然在教程部分,但我正在考慮我需要將數據從前端(select 選項)傳遞到后端,以確定我將從數據庫中獲得的分支和費用類型。 如果直接從錨標簽中的 href="/sampleRoute" 下載,它將下載,但如果我嘗試通過 ajax 下載 go,則不會。

我的路線的代碼示例,ajax 和 controller。 controller 中的代碼直接來自教程,但 ajax 只是我在嘗試別的東西。

路線

Route::get('/excel_tf_breakdown', 'excelController@excel_tf_breakdown');

AJAX

$(document).on('click', '#btnExport', function(){
    test = 'test';

    $.ajax({
        url: '/excel_tf_breakdown',
        data: {
            test:test
        },
        method: 'get',
        dataType: 'json',
        success:function(data){
        }
    });
});

CONTROLLER

public function excel_tf_breakdown(Request $request){
    info($request->test);

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', '#');
    $sheet->setCellValue('A2', 'First');
    $sheet->setCellValue('A3', 'First');
    $sheet->setCellValue('A4', 'First');

    $filename = 'sample.xlsx';

    //redirect output to client
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="'.$filename.'"');
    header('Cache-Control: max-age=0');

    $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
    exit;
}

請求->測試有效,但它不下載 excel 文件。 我想知道如何使用 ajax 導出到 excel。

做一件事,

$(document).on('click', '#btnExport', function(){
    test = 'test';

    $.ajax({
        url: '/excel_tf_breakdown',
        data: {
            test:test
        },
        method: 'get',
        dataType: 'json',
        success:function(data){
            window.open('http://YOUR_URL','_blank' ); // You need to do this only.
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM