6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでExcel

Last updated at Posted at 2017-12-05

PHPExcelの使い方メモです。

補足

インストール

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

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?