答案:使用PhpSpreadsheet库可实现PHP对Excel文件的生成、读取与下载。首先通过Composer安装库,创建Spreadsheet对象并填充数据,设置正确的响应头(如Content-Type和Content-Disposition),最后调用Xlsx写入器将文件输出到浏览器触发下载;对于已有文件,可通过readfile()配合响应头强制下载;上传文件则使用IOFactory读取内容并处理。注意清除输出缓冲,避免文件损坏。

要实现 PHP 操作 Excel 文件并支持下载,通常需要借助第三方库来读取或生成 Excel 文件,然后通过浏览器触发下载。以下是常用方法和步骤,帮助你快速实现 PHP 下载 Excel 文件以及操作 Excel 内容。
PhpSpreadsheet 是目前最流行的 PHP 库,用于读写 Excel (.xlsx) 和其他电子表格格式。它是PHPExcel的继任者,功能强大且维护活跃。
1. 安装 PhpSpreadsheetcomposer require phpoffice/phpspreadsheet
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// 创建一个新的 Spreadsheet 对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', '姓名');
$sheet->setCellValue('B1', '年龄');
$sheet->setCellValue('A2', '张三');
$sheet->setCellValue('B2', '25');
// 设置下载响应头
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="users.xlsx"');
header('Cache-Control: max-age=0');
// 使用 Xlsx 写入器
$writer = new Xlsx($spreadsheet);
$writer->save('php://output'); // 输出到浏览器,触发下载
将以上代码保存为 download_excel.php,访问该页面会直接弹出下载对话框。
立即学习“PHP免费学习笔记(深入)”;
如果你已有 Excel 文件在服务器上,可以通过 PHP 读取并强制用户下载。
<?php
$filePath = 'uploads/template.xlsx'; // 文件路径
if (file_exists($filePath)) {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Cache-Control: max-age=0');
readfile($filePath);
exit;
} else {
echo "文件未找到!";
}
如果需要处理用户上传的 Excel 文件,可以使用 PhpSpreadsheet 读取数据。
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
if ($_FILES['excelFile']['error'] == 0) {
$inputFileName = $_FILES['excelFile']['tmp_name'];
try {
$spreadsheet = IOFactory::load($inputFileName);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
foreach ($sheetData as $row) {
print_r($row); // 输出每一行数据
}
} catch (Exception $e) {
echo 'Error loading file: ', $e->getMessage();
}
}
配合 HTML 表单上传:
<form method="post" enctype="multipart/form-data">
<input type="file" name="excelFile" accept=".xlsx,.xls" />
<button type="submit">上传并读取</button>
</form>ob_clean() 和 flush() 可防止缓冲问题:
ob_end_clean(); // 清除缓冲区
$writer->save('php://output');以上就是如何下载php excel文件_获取php操作excel文件的相关文件方法的详细内容,更多请关注php中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号