要使用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文件了。