Not saving excel with PHPSpreadsheet in symfony 4

Viewed 499

I'm using "phpoffice/phpspreadsheet": "^1.13", can not save updates into uploaded file. I can read data from it but can not save. The other thing to mention I am running it in the Process in background.

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;

//read from file
$reader = new Xlsx();
$reader->setLoadSheetsOnly(["Gifts"]);
$spreadsheet = $reader->load($file);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();

for ($row = 5; $row < $highestRow; $row++) {
  $results[] = [
    'id' => $worksheet->getCell('K'.$row)->getValue(),
  ];
}

//write to file
$spreadsheet = IOFactory::load($file);
$sheet = $spreadsheet->getSheetByName('Gifts');
$sheet->setCellValue('A1', 'Import Status');
$writer = new XlsxWriter($spreadsheet);
ob_end_clean();
$writer->save($file);

If not use ob_end_clean(); the file is saving corrupt and LibbreOffice cannot open it with ob_end_clean(); the file is opening but without changes.

The purpose is to create entities in db reading data from Excel, but because the file can be large I want to run it in the background, maybe it is not the best approach but the best I could do for now so the process is as follows:

  1. upload file
  2. start new process
Process::fromShellCommandline('php /var/www/app/bin/console app:import:excel "'.$file.'"')->start();
  1. redirect user to another page
  2. send an email with a report of imported stuff

All the steps are working fine except saving Excel, when I am opening the uploaded file it does not have any changes, in other question I have found advice like to add ob_end_clean(); or die() it helped at least to open the file without ob_end_clean(); it shows that it is broken.

0 Answers
Related