PHPExcel 是一个用于处理 Excel 文件的 PHP 库,可以用来读取、写入和操作 Excel 文件。AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
以下是一个使用 PHPExcel 和 AJAX 实现 Excel 文件导出的示例:
<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// 创建一个新的 Spreadsheet 对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 设置单元格内容
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B1', 'World');
// 创建一个 Writer 对象
$writer = new Xlsx($spreadsheet);
// 设置响应头
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="export.xlsx"');
header('Cache-Control: max-age=0');
// 将 Excel 文件写入输出流
$writer->save('php://output');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Export Excel</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="export-btn">Export Excel</button>
<script>
$(document).ready(function() {
$('#export-btn').click(function() {
$.ajax({
url: 'export.php',
method: 'GET',
xhrFields: {
responseType: 'blob'
},
success: function(data) {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = 'export.xlsx';
link.click();
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
});
});
</script>
</body>
</html>
Content-Disposition
头部设置正确。Content-Type
头部设置正确。通过以上步骤,你应该能够成功实现使用 PHPExcel 和 AJAX 导出 Excel 文件的功能。
领取专属 10元无门槛券
手把手带您无忧上云