LoginSignup
2
1

More than 3 years have passed since last update.

参考

環境

  • PHP 5.6
  • Laravel 5.4
  • LaravelExcel 2.1
  • XLSXWriter

LaravelExcelを利用し、DBから取得したデータをExcelファイルに書き込んでExportする処理を作っていたが、データ件数が大量になると

Allowed memory size of ○○○○○ bytes exhausted

というメモリオーバーのエラーが出た。

PHPでExcelファイルを作成する際にはしばしばぶち当たるこの問題。
今回は顧客の要望をまったく満たせないパフォーマンスだったので、ライブラリをXLSXWriterに変更してみた。

パッケージのインストール

composer require mk-j/PHP_XLSXWriter

簡単な使い方


use XLSXWriter;

// 中略

// シート名
const SHEET_NAME = 'ユーザーリスト';

// ヘッダー情報
const SHEET_HEADER = [
    'ID' => 'integer',
    'NAME' => 'string',
    'BIRTHDAY' => 'yyyy/mm/dd',
];

$writer = new XLSXWriter();

// ヘッダー行の書き込み
$writer->writeSheetHeader(self::SHEET_NAME, self::SHEET_HEADER);

// データ行書き込み
foreach ($dataList as $data) {
    $writer->writeSheetRow(self::SHEET_NAME, $data);
}

// 出力
$filePath = './tmp/user_list.xlsx';
$writer->writeToFile($filePath);

// XLSXWriterはストレージに保存するしか方法がない?ようなので、Exportしたい時は出力後ファイル削除
if (file_exists($filePath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filePath));
    $readFile = readfile($filePath);
    if ($readFile) {
        unlink($filePath);
    }
}
exit;
2
1
1

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
2
1