Files
nuhodds_fi4/app/Traits/GrappingToExcel.php
T
2026-09-26 17:49:06 +02:00

86 lines
2.6 KiB
PHP

<?php
namespace App\Traits;
use App\Utilities\Notice;
use Illuminate\Support\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
trait GrappingToExcel
{
public static $max = 2000;
public function import_to_excel(string $folder)
{
ini_set('memory_limit', -1);
if ($this->debug) {
Notice::note("import $folder to excel", 'g');
}
$titel = ucfirst($folder).'_'.Carbon::now()->format('Y-m-d');
$files = $this->get_tree("$this->data_dir/$folder");
$files = array_chunk($this->filter($files), self::$max);
foreach ($files as $key => $value) {
$has = count($value);
if (! $key && $has < self::$max) {
$from = 1;
$to = $has;
} elseif (! $key) {
$from = 1;
$key++;
$to = $key * self::$max;
} elseif ($has == self::$max) {
$from = $key * self::$max + 1;
$key++;
$to = $key * self::$max;
} else {
$from = $key * self::$max + 1;
$to = $key * self::$max + $has;
}
$spreadsheet = new Spreadsheet;
$spreadsheet->getProperties()->setTitle("$titel-$from-$to");
$activeWorksheet = $spreadsheet->getActiveSheet();
$column = 1;
foreach ($value as $file) {
$data = file_get_contents($file);
$data = json_decode($data, true);
$json_string = json_encode($data, JSON_PRETTY_PRINT);
$arr = explode(PHP_EOL, $json_string);
$row = 0;
foreach ($arr as $string) {
$row++;
$replacedString = preg_replace('/\\\\u([0-9abcdef]{4})/', '&#x$1;', $string);
$utf8string = mb_convert_encoding($replacedString, 'UTF-8', 'HTML-ENTITIES');
$activeWorksheet->setCellValue([$column, $row], $utf8string);
}
$column++;
}
$spreadsheet->setActiveSheetIndex(0);
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save("$titel-$from-$to.xlsx");
}
}
protected function filter(array $files, array $types = ['json'])
{
$filtered = [];
foreach ($files as $file) {
$path_parts = pathinfo($file);
if (isset($path_parts['extension']) && in_array($path_parts['extension'], $types)) {
$filtered[] = $file;
}
}
return $filtered;
}
}