You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AJAX将JS数组传给PHP,用SimpleXLSXGen生成下载Excel

解决AJAX传递JSON生成并下载Excel文件的问题

核心问题说明

AJAX无法直接触发浏览器的文件下载行为,且若PHP返回过程中输出错误信息,会导致下载的文件混入HTML代码而损坏。以下是三种可行的实现方案:


方案一:Base64编码传输,前端触发下载

通过AJAX将JSON传给PHP,PHP生成Excel后返回Base64编码,前端解码并创建下载链接。

前端代码

// 待传递的JSON数组
const excelData = [
    ['姓名', '年龄', '城市'],
    ['张三', 25, '北京'],
    ['李四', 30, '上海']
];

fetch('generate-excel.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(excelData)
})
.then(res => res.json())
.then(result => {
    if (result.success) {
        // 创建临时下载链接
        const link = document.createElement('a');
        link.href = `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,${result.base64}`;
        link.download = '用户数据.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } else {
        alert('Excel生成失败:' + result.error);
    }
})
.catch(err => console.error('请求异常:', err));

PHP代码(generate-excel.php)

<?php
require 'SimpleXLSXGen.php';

// 接收JSON数据
$rawData = file_get_contents('php://input');
$data = json_decode($rawData, true);

if (!$data) {
    echo json_encode(['success' => false, 'error' => '无效的JSON数据']);
    exit;
}

// 生成Excel并转为Base64
$xlsx = Shuchkin\SimpleXLSXGen::fromArray($data);
$base64Content = base64_encode($xlsx->output());

echo json_encode(['success' => true, 'base64' => $base64Content]);
?>

方案二:隐藏表单POST提交(无需AJAX)

直接通过创建隐藏表单提交JSON数据,PHP直接输出下载响应,浏览器自动触发下载。

前端代码

const excelData = [
    ['姓名', '年龄', '城市'],
    ['张三', 25, '北京'],
    ['李四', 30, '上海']
];

// 创建临时表单
const form = document.createElement('form');
form.method = 'POST';
form.action = 'download-excel.php';

// 添加隐藏字段存储JSON
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'excelData';
input.value = JSON.stringify(excelData);

form.appendChild(input);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);

PHP代码(download-excel.php)

<?php
require 'SimpleXLSXGen.php';

if (!isset($_POST['excelData'])) {
    die('缺少数据参数');
}

$data = json_decode($_POST['excelData'], true);
if (!$data) {
    die('无效的JSON数据');
}

// 直接生成并触发下载
$xlsx = Shuchkin\SimpleXLSXGen::fromArray($data);
$xlsx->download('用户数据.xlsx');
?>

方案三:AJAX接收Blob对象,前端处理下载

PHP返回二进制Excel数据,前端通过Blob对象创建下载链接。

前端代码

const excelData = [
    ['姓名', '年龄', '城市'],
    ['张三', 25, '北京'],
    ['李四', 30, '上海']
];

fetch('excel-blob.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(excelData)
})
.then(res => res.blob())
.then(blob => {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户数据.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url); // 释放内存
})
.catch(err => console.error('请求异常:', err));

PHP代码(excel-blob.php)

<?php
require 'SimpleXLSXGen.php';

$rawData = file_get_contents('php://input');
$data = json_decode($rawData, true);

if (!$data) {
    http_response_code(400);
    echo '无效的JSON数据';
    exit;
}

$xlsx = Shuchkin\SimpleXLSXGen::fromArray($data);
$excelContent = $xlsx->output();

// 设置正确的响应头,避免文件损坏
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="用户数据.xlsx"');
header('Content-Length: ' . strlen($excelContent));

echo $excelContent;
?>

常见问题排查

  • 若下载的文件为HTML格式:检查PHP是否输出了错误信息(如语法错误、路径错误),可开启PHP错误日志排查,避免直接输出错误到响应中。
  • 确保SimpleXLSXGen库文件路径正确,无引入错误。

内容的提问来源于stack exchange,提问作者Ac. Selvan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:45:39