composer require phpoffice/phpspreadsheet
接下来,在你的 PHP 文件中使用 PhpSpreadsheet
创建和导出一个 Excel 文件。以下是一个示例代码:
<?php
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!');
// 如果有更多数据,可以用循环设置单元格的值
$data = [
['Name', 'Age', 'Email'],
['John Doe', 28, 'john@example.com'],
['Jane Smith', 32, 'jane@example.com'],
];
$row = 1;
foreach ($data as $rowData) {
$col = 'A';
foreach ($rowData as $cellData) {
$sheet->setCellValue($col . $row, $cellData);
$col++;
}
$row++;
}
// 将电子表格保存为文件
$writer = new Xlsx($spreadsheet);
$filename = 'example.xlsx';
// 将文件保存到服务器
$writer->save($filename);
// 或者直接输出到浏览器进行下载
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
3. 解释代码
<?php
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="example.csv"');
$output = fopen('php://output', 'w');
// 写入 CSV 文件的头部
fputcsv($output, ['Name', 'Age', 'Email']);
// 写入数据
$data = [
['John Doe', 28, 'john@example.com'],
['Jane Smith', 32, 'jane@example.com'],
];
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
exit;
2. 使用旧版 PHPExcel 库
<?php
require 'path/to/PHPExcel.php';
// 创建一个新的 PHPExcel 对象
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
// 设置单元格的值
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'World!');
// 如果有更多数据,可以用循环设置单元格的值
$data = [
['Name', 'Age', 'Email'],
['John Doe', 28, 'john@example.com'],
['Jane Smith', 32, 'jane@example.com'],
];
$row = 1;
foreach ($data as $rowData) {
$col = 'A';
foreach ($rowData as $cellData) {
$objPHPExcel->getActiveSheet()->setCellValue($col . $row, $cellData);
$col++;
}
$row++;
}
// 将电子表格保存为文件
$filename = 'example.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;