PHP导出Excel文件通常是指使用PHP编程语言将数据输出为Excel格式的文件,以便用户可以在Microsoft Excel或其他兼容的电子表格软件中打开和编辑这些文件。这种操作在数据处理、报表生成、数据备份等场景中非常常见。
以下是一个使用PHP导出XLSX文件的示例代码:
<?php
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="data.xlsx"');
header('Cache-Control: max-age=0');
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// 创建一个新的Spreadsheet对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 设置表头
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Name');
$sheet->setCellValue('C1', 'Email');
// 填充数据
$data = [
['1', 'John Doe', 'john@example.com'],
['2', 'Jane Smith', 'jane@example.com'],
// 更多数据...
];
foreach ($data as $row => $rowData) {
foreach ($rowData as $col => $cellData) {
$sheet->setCellValueByColumnAndRow($col + 1, $row + 2, $cellData);
}
}
// 创建一个写入器并保存文件
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
?>
原因:
解决方法:
原因:
解决方法:
$spreadsheet->getDefaultStyle()->getFont()->setName('Arial Unicode MS');
通过以上方法,可以有效解决PHP导出Excel文件时遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云