PHP实现excel
PHP 实现 Excel 操作
读取 Excel 文件
使用 PHP 读取 Excel 文件可以通过 PhpSpreadsheet 库实现。安装该库可以通过 Composer:
composer require phpoffice/phpspreadsheet
读取 Excel 文件的基本代码示例:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
$inputFileName = 'example.xlsx';
$spreadsheet = IOFactory::load($inputFileName);
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
echo $cell->getValue() . "\t";
}
echo "\n";
}
写入 Excel 文件
使用 PhpSpreadsheet 创建和写入 Excel 文件的示例:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B1', 'World');
$writer = new Xlsx($spreadsheet);
$writer->save('output.xlsx');
导出 Excel 文件
将数据导出为 Excel 文件并直接下载:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Name');
$sheet->setCellValue('B1', 'Email');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="export.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
处理 CSV 文件
如果需要处理 CSV 文件,可以使用 PHP 内置函数:
// 读取 CSV
if (($handle = fopen("input.csv", "r")) !== false) {
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
print_r($data);
}
fclose($handle);
}
// 写入 CSV
$list = [['Name', 'Email'], ['John', 'john@example.com']];
$fp = fopen('output.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
使用其他库
除了 PhpSpreadsheet,还可以使用 PHPExcel(已弃用)或 SimpleExcel 等库。PhpSpreadsheet 是目前最推荐的解决方案。
注意事项
- 确保服务器有足够的权限读写文件。
- 处理大文件时,注意内存使用情况,可以分块读取或使用流式处理。
- 导出文件时,确保设置正确的 HTTP 头以避免文件损坏。
以上方法涵盖了 PHP 中操作 Excel 文件的常见需求,包括读取、写入和导出。







