PHPExcelの使い方メモです。
補足
- PHPExcelの新バージョンとしてPhpSpreadsheetが出ているようです。
- PhpSpreadsheetでもメモリの問題はあるようで、メモリ消費の少ないPHP_XLSXWriterというのもあるみたいです。
php-excel-writer-performance-comparison - 性能ならLibXL PHP LICENSE
インストール
composer require phpoffice/phpexcel
基本的な使い方例
上記の例ようなB5等のセル位置を指定する方法よりも以下の列と行をしていする方法の方が便利そうです。
// Set cell B5 with a string value
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 5, 'PHPExcel');
メモリ設定
PHPExcelはメモリを多く使うので使用する際には以下の設定を行っておくと良さそう。
// ファイルキャッシュに変更(遅くなるがメモリを大幅に減少)
PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_to_discISAM, ['dir' => '/tmp']);
まとめ
// Excel作成
PHPExcel_Settings::setCacheStorageMethod(
PHPExcel_CachedObjectStorageFactory::cache_to_discISAM,
['dir' => '/tmp']
);
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objSheet = $objPHPExcel->getActiveSheet();
$xlsx_data = [
['A1', 'B1', 'C1'],
['A2', 'B2', 'C1'],
];
foreach ($xlsx_data as $row_index => $row_data)
{
foreach ($row_data as $column_index => $column_data)
{
$objSheet->setCellValueByColumnAndRow($column_index, $row_index + 1, $column_data);
}
}
$current_datetime = new DateTimeImmutable(date('Y-m-d H:i:s'));
$file_name = 'test_' . $current_datetime->format('YmdHis') . '.xlsx';
$file_path = '/home/public/app/tmp/' . $file_name;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($file_path);
参考
https://qiita.com/nwsoyogi/items/a25d2bc050d53a79ab93
http://www.zedwood.com/article/php-excel-writer-performance-comparison