テンプレートの読込と出力

Demo

sample.phpExcelテンプレートファイル(template.xlsx)

PHP

PHPindex.phpdownload

<?php

	require_once 'vendor/autoload.php';

	/* テンプレート読み込み */
	$reader = PHPExcel_IOFactory::createReader('Excel2007');

	$spreadsheet = $reader->load('template.xlsx');	//読み込むテンプレートを設定

	/* シートを設定する */
	$spreadsheet->setActiveSheetIndex(0);			//一番最初のシートを選択, 2枚目の場合は(1)

	$sheet = $spreadsheet->getActiveSheet();			//選択シートにアクセス

	$sheet->setTitle( 'Sheet1' );						//シート名を設定

	/* 値とセルを指定 */
	$sheet->setCellValue('A2', 'りんご');

	$sheet->setCellValue('A3', 'いちご');

	$sheet->setCellValue('A4', 'もも');

	/* Excelファイルのダウンロード */
	$fileName = "sample.xlsx";	//ダウンロード時のファイル名を設定

	header("Content-Description: File Transfer");

	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');	//vnd.openxmlformats-officedocument.spreadsheetml.sheet:EXCELファイル( .xlsx OFFICE 2007以降), vnd.ms-excel:EXCELファイル( .xls OFFICE 2007より過去)

	header('Content-Disposition: attachment; filename="'.$fileName.'"');	//ダウンロード時のファイル名をセット

	header('Cache-Control: no-store, max-age=0');	//新しいリソースのキャッシュを防止、キャッシュのクリア

	ob_end_clean();	//バッファ消去

	$writer = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel2007');	//Excel5:Excel97~2003, Excel2007:Excel2007~

	$writer->save('php://output');
?>
© 2025 wayday