Load graphics with phpSpreedSheet

Viewed 725

I am using PhpSpreedSheet to load an excel, update it and save it again ... The problem I find is that it does not save it well for the graphics, and when you open the excel it tells you the typical thing that there has been a problem and "Do you want that we try to recover as much content as possible? " and remove the graphics.

Excel has completed validation and repair at the file level. Some parts of this book may have been repaired or discarded. Part removed: Part Properties of the document. (Drawing form) Part removed: Drawing form. Removed part: Drawing form.

    $reader = IOFactory::createReader('Xlsx');
    $reader->setIncludeCharts(true);


    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($this->spreadsheet);
    $writer->setIncludeCharts(true);
1 Answers

To include a drawing you should use something like this:

$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Logo');
$drawing->setDescription('Logo');
$drawing->setPath('./images/officelogo.jpg');
$drawing->setCoordinates('B15');
$drawing->setHeight(36);

$drawing->setWorksheet($spreadsheet->getActiveSheet());

For reading out of all images you should use the code from the documentation:

$i = 0;
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
    if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
        ob_start();
        call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
        );
        $imageContents = ob_get_contents();
        ob_end_clean();
        switch ($drawing->getMimeType()) {
            case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG :
                $extension = 'png';
                break;
            case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
                $extension = 'gif';
                break;
            case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG :
                $extension = 'jpg';
                break;
        }
    } else {
        $zipReader = fopen($drawing->getPath(),'r');
        $imageContents = '';
        while (!feof($zipReader)) {
            $imageContents .= fread($zipReader,1024);
        }
        fclose($zipReader);
        $extension = $drawing->getExtension();
    }
    $myFileName = '00_Image_'.++$i.'.'.$extension;
    file_put_contents($myFileName,$imageContents);
}
Related