Skip to content

Instantly share code, notes, and snippets.

@lechuhuuha
Created January 8, 2024 09:23
Show Gist options
  • Save lechuhuuha/ef73c22f39a4432b6436372aa22a8739 to your computer and use it in GitHub Desktop.
Save lechuhuuha/ef73c22f39a4432b6436372aa22a8739 to your computer and use it in GitHub Desktop.
Box Spout php excel for large file
<?php
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
function genLogs($progressCallback, $defaultHeader, $customHeader, $ipHeader = [], $model, $total)
{
$headers = array_merge($defaultHeader, array_values($customHeader), $ipHeader);
$model = '\EMA\Model\MongoDB\\' . $model;
$tmpTableName = 'log_' . $this->uid . '_' . md5(rand());
$filePath = storage_path(join_paths('app/tmp/export', $tmpTableName . '.xlsx'));
$lastId = null;
$writer = WriterEntityFactory::createXLSXWriter();
$writer->openToFile($filePath); // write data to a file or to a PHP stream
// add headers
$headers = WriterEntityFactory::createRowFromArray($headers);
$writer->addRow($headers);
$limit = 20;
$pages = ceil($total / $limit);
$i = 0;
if ($total > 0) {
while (true) {
$rowToInsert = [];
foreach ($logs as $log) {
$rowToInsert = $log;
}
// add single row to excel
foreach ($rowToInsert as $row) {
$rowFromValues = WriterEntityFactory::createRowFromArray($row);
$writer->addRow($rowFromValues);
}
// callback progress
if (!is_null($progressCallback)) {
$percentage = ($i + 1) / $pages;
$progressCallback($percentage, $filePath);
}
$i = $i + 1;
}
}
$writer->close();
// callback progress
if (!is_null($progressCallback)) {
$progressCallback($percentage = 100, $filePath);
}
return $filePath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment