在函数中使用PHPSpreadsheet类,可以通过以下步骤完成:
require_once 'path/to/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
创建一个新的Excel文件对象,或者使用$spreadsheet = IOFactory::load('path/to/excel_file.xlsx');
打开现有的Excel文件。$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B1', 'World!');
$style = [
'font' => [
'bold' => true,
'color' => ['rgb' => 'FF0000'],
],
];
$sheet->getStyle('A1')->applyFromArray($style);
$data = [
['Name', 'Age', 'City'],
['John Doe', 25, 'New York'],
['Jane Smith', 30, 'London'],
];
$sheet->fromArray($data, null, 'A2');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
创建一个写入器对象,并通过$writer->save('path/to/save.xlsx');
保存Excel文件到指定路径,或者通过$writer->save('php://output');
输出Excel文件到浏览器。以下是完整的示例代码:
require_once 'path/to/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
function generateExcel() {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 添加数据到单元格
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B1', 'World!');
// 设置单元格样式
$style = [
'font' => [
'bold' => true,
'color' => ['rgb' => 'FF0000'],
],
];
$sheet->getStyle('A1')->applyFromArray($style);
// 创建表格
$data = [
['Name', 'Age', 'City'],
['John Doe', 25, 'New York'],
['Jane Smith', 30, 'London'],
];
$sheet->fromArray($data, null, 'A2');
// 保存或输出Excel文件
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('path/to/save.xlsx');
}
generateExcel();
推荐的腾讯云相关产品:腾讯云对象存储(COS)可以用于存储生成的Excel文件。详情请参考腾讯云对象存储产品介绍:https://cloud.tencent.com/product/cos。
领取专属 10元无门槛券
手把手带您无忧上云