要使用PHP的PHPExcel(现在称为PhpSpreadsheet)库创建工作表,请按照以下步骤操作:
composer require phpoffice/phpspreadsheet
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 或者
$sheet = $spreadsheet->createSheet('New Sheet');
// 设置标题行的样式
$titleStyle = [
'font' => [
'bold' => true,
],
];
// 写入标题行
$titles = ['Column1', 'Column2', 'Column3'];
$colCount = count($titles);
foreach ($titles as $colIndex => $title) {
$sheet->setCellValueByColumnAndRow($colIndex + 1, 1, $title, $titleStyle);
}
// 设置列宽
$sheet->getColumnDimension('A')->setWidth(10);
$sheet->getColumnDimension('B')->setWidth(20);
$sheet->getColumnDimension('C')->setWidth(30);
// 创建一个Xlsx写入器
$writer = new Xlsx($spreadsheet);
// 将工作表写入Excel文件
$fileName = 'example.xlsx';
$writer->save($fileName);
这样,你就可以使用PhpSpreadsheet库在PHP中创建工作表并将数据写入Excel文件了。