如何在PHP中保存Excel文件?点击按钮生成并下载Excel的实现
PHP生成并下载Excel文件的解决方案(适配你的CURL请求场景)
咱先梳理下你的需求:点击按钮后从数据库取数生成Excel供下载,当前是通过PHP的CURL请求指定接口来实现。先给你把现有代码的问题修正,再给你一套完整的可运行方案。
一、先修正你现有CURL代码的问题
你的代码里有几个细节错误,先改过来:
- 变量名写错:你定义了
$PlaceIdx = $_REQUEST['Idx'];,但后面用了$post_data["Idx"] = $Idx;,这里应该用$PlaceIdx - HTTP头拼写错误:
appliaction/json→application/json - JSON请求需要把POST数据转为JSON字符串,而不是直接传数组
修正后的CURL代码片段:
<?php $PlaceIdx = $_REQUEST['Idx']; $Day = $_REQUEST['Day']; $url = '#url'; // 替换成你的生成Excel的接口URL // 构造POST数据并转为JSON $post_data = [ "Idx" => $PlaceIdx, "Day" => $Day ]; $json_data = json_encode($post_data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 修正Content-Type拼写,并设置JSON请求头 curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json_data) ]); // 传入JSON格式的POST数据 curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // 执行请求并处理结果 $response = curl_exec($ch); $error = curl_error($ch); curl_close($ch); // 如果是要直接触发下载,这里可以把响应输出给前端 if (!$error) { // 假设后端接口返回的是Excel文件流,直接输出并设置下载头 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="data.xlsx"'); header('Cache-Control: max-age=0'); echo $response; } else { echo "请求错误:" . $error; } ?>
二、后端生成Excel的接口实现(推荐用PhpSpreadsheet)
现在PHPExcel已经停止维护了,推荐用官方替代的PhpSpreadsheet,这是目前最稳定的Excel操作库。
1. 先安装PhpSpreadsheet
用Composer安装(如果没装Composer可以先去官网安装):
composer require phpoffice/phpspreadsheet
2. 生成Excel的接口脚本(比如generate_excel.php)
这个脚本接收CURL传过来的Idx和Day,从数据库取数据,生成Excel并输出:
<?php require 'vendor/autoload.php'; // 引入Composer自动加载 use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; // 接收JSON格式的POST数据 $input = json_decode(file_get_contents('php://input'), true); $Idx = $input['Idx'] ?? ''; $Day = $input['Day'] ?? ''; // 1. 从数据库获取数据(这里替换成你的数据库查询逻辑) // 示例:假设用PDO查询 $pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password'); $stmt = $pdo->prepare("SELECT * FROM your_table WHERE idx = ? AND day = ?"); $stmt->execute([$Idx, $Day]); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); // 2. 创建Excel对象并填充数据 $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // 设置表头(根据你的数据字段调整) $sheet->setCellValue('A1', 'ID'); $sheet->setCellValue('B1', '名称'); $sheet->setCellValue('C1', '日期'); // 填充数据 $row = 2; foreach ($data as $item) { $sheet->setCellValue('A' . $row, $item['id']); $sheet->setCellValue('B' . $row, $item['name']); $sheet->setCellValue('C' . $row, $item['day']); $row++; } // 3. 设置下载头并输出Excel header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="data_' . $Day . '.xlsx"'); header('Cache-Control: max-age=0'); $writer = new Xlsx($spreadsheet); // 直接输出到浏览器,不保存到服务器 $writer->save('php://output'); exit; ?>
三、前端按钮的触发逻辑
如果是前端点击按钮触发这个PHP请求,你可以用表单提交或者AJAX(注意AJAX下载需要处理blob),比如用简单的表单:
<form method="post" action="你的CURL脚本路径.php"> <input type="hidden" name="Idx" value="123"> <!-- 替换成实际的Idx值 --> <input type="hidden" name="Day" value="2024-05-20"> <!-- 替换成实际的日期 --> <button type="submit">下载Excel</button> </form>
这样一套流程走下来,点击按钮后,前端提交请求到你的CURL脚本,脚本请求后端生成Excel的接口,拿到文件流后输出给浏览器,就能触发下载了。
内容的提问来源于stack exchange,提问作者Polaris Nation
相关产品推荐
相关产品推荐

