4

I have generated a valid spreadsheet and I am able to save it with the documented save method :

$writer = new Xlsx($spreadsheet);
$writer->save('file.xlsx');

But how can I use the storages disks provided by Laravel ? Can I get the content of the file before writing it to the disk ?

Neekobus
  • 1,870
  • 1
  • 14
  • 18

3 Answers3

11

I figured out by myself. Since there is no $writer->getContent() method here is my workaround :

  • Save to php://output
  • Capture the file content with ob_start/ob_get_contents.
  • Finally call the regular Storage put() method on any disk !

Here is my code :

    $writer = new Xlsx($spreadsheet);

    ob_start();
    $writer->save('php://output');
    $content = ob_get_contents();
    ob_end_clean();

    Storage::disk('local')->put("myfile.xlsx", $content); 
    Storage::disk('myftp')->put("myfile.xlsx", $content); 
Neekobus
  • 1,870
  • 1
  • 14
  • 18
1

It's possible to let PHPSpreadsheet write to a resource. In this case a temporary file.

$resource = tmpfile();

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($resource);

Storage::disk('public')->put('filename.csv', $resource);
  • 1
    It works for me in local. But will tmpfile function cause any issue in prod? Let me see and come back with result. – Nur Uddin Aug 21 '22 at 00:56
0

Try using the method I wrote.

public function generateExcelDownload($file = '/public/excel/')
{
    $spreadsheet = new Spreadsheet();
    $sheet       = $spreadsheet->getActiveSheet();
    $styleArray  = [
        'borders'   => [
            'allBorders' => [
                'borderStyle' => Border::BORDER_THIN,
            ],
        ],
        'alignment' => [
            'wrapText' => true,
        ],
        'font'      => [
            //'size' => 14,
        ],
    ];

    $this->excelHeaderGenerate($sheet, $styleArray);
    $this->excelBodyGenerate($spreadsheet, $styleArray);

    $writer = new Xlsx($spreadsheet);
    $writer->setPreCalculateFormulas(false);
    $file_dir = dirname(__DIR__, 3).$file;
    if (!file_exists($file_dir)) {
        if (!mkdir($file_dir, 0777, true) && !is_dir($file)) {
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $file));
        }
    }
    $file = $file_dir.date('Y-m-d_H-i-s').'.xlsx';
    $writer->save($file);

    return $file;
}
Akbarali
  • 688
  • 7
  • 16