I have been trying to extract images and charts from an Xlsx file using the phpspreadsheet libray; I have however been unsuccessful.
Indeed, the piece of code I wrote is unable to find any image or chart from my xlsx file.
However, when I convert the file from Xlsx to Xls using Excel, the same code works and manages to extract images and charts.
This is the code i use to load my spreadsheet :
$fileType = PhpOfficePhpSpreadsheetIOFactory::identify($filePath); $reader = PhpOfficePhpSpreadsheetIOFactory::createReader($fileType); $spreadsheet = $reader->load($filePath);
And then I added the code provided by the official documentation :
$i = 0; foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) { if ($drawing instanceof PhpOfficePhpSpreadsheetWorksheetMemoryDrawing) { ob_start(); call_user_func( $drawing->getRenderingFunction(), $drawing->getImageResource() ); $imageContents = ob_get_contents(); ob_end_clean(); switch ($drawing->getMimeType()) { case PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_PNG : $extension = 'png'; break; case PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::MIMETYPE_GIF: $extension = 'gif'; break; case PhpOfficePhpSpreadsheetWorksheetMemoryDrawing::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); }
The above code works with an .xls file but not with an .xlsx : the getDrawingCollection
and/or getChartCollection
return an empty array with .xlsx files…
Do any of you guys know how to perform this? I’m open to any solution… even if it means converting the file via another library…
Thanks in advance,
Advertisement
Answer
I found the solution… one line of code, to add after initializing the reader :
$reader->setIncludeCharts(true);