TYPO3 v12: Return a phpoffice spreadsheet in a response object

raw

Controller.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Ods;
 
use Psr\Http\Message\ResponseInterface;
 
class Controller
{
    public function exportAction(): ResponseInterface
    {
        $spreadsheet = new Spreadsheet();
        $activeWorksheet = $spreadsheet->getActiveSheet();
        $activeWorksheet->setCellValue('A1', 'Hello World !');
 
        $writer = new Ods($spreadsheet);
 
        return $this->responseFactory->createResponse()
            ->withHeader('Content-Type', 'application/vnd.oasis.opendocument.spreadsheet')
            ->withBody(new SpreadsheetStream($writer));
    }
 
}
raw

SpreadsheetStream.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
 
declare(strict_types=1);
 
use PhpOffice\PhpSpreadsheet\Writer\BaseWriter;
 
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
use TYPO3\CMS\Core\Http\SelfEmittableStreamInterface;
 
/**
 * Generate a spreadsheet in the last moment for downloading
 */
class SpreadsheetStream implements StreamInterface, SelfEmittableStreamInterface
{
    use StreamDecoratorTrait;
 
    public function __construct(
        protected readonly BaseWriter $writer
    ) {}
 
    /**
     * Emit the response to stdout, as specified in SelfEmittableStreamInterface.
     */
    public function emit()
    {
        $this->writer->save('php://output');
    }
 
    public function isWritable(): bool
    {
        return false;
    }
 
    /**
     * @throws \RuntimeException
     */
    public function write(string $string): int
    {
        throw new \RuntimeException('Cannot write to a ' . self::class, 1538331852);
    }
}
 
Christian Weiske Christian Weiske
owner

History