$(document).ready(function () {
$('#exportButton').click(function () {
$.ajax({
url: '{:url('admin/excel/export')}',
method: 'POST',
xhrFields: {
responseType: 'blob'
},
success: function (data) {
var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'example.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
},
error: function (xhr, status, error) {
}
});
});
});
<?php
namespace app\admin\controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Excel
{
public function export()
{
$spreadsheet = new Spreadsheet();
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="example.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
}
}