A
A
Aricus2019-01-11 22:39:44
PHP
Aricus, 2019-01-11 22:39:44

PhpSpreadsheet: how to add an image (gif) to excel?

I need to add an image to excel using PhpSpreadsheet. According to the documentation https://phpspreadsheet.readthedocs.io/en/latest/to... generated the following code:

require_once(getenv('DOCUMENT_ROOT')."/".explode('/',$_SERVER["REQUEST_URI"])[1]."/test/vendor/autoload.php");
    $Reader = new PhpOffice\PhpSpreadsheet\Reader\Xlsx();
    $spreadsheet = $Reader->load('..\..\templates\somefile.xlsx');
    /* Тест: загрузка картинок */
    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
    $drawing->setName('Logo');
    $drawing->setDescription('Logo');
    $drawing->setPath('../img/barcode.gif');
    $drawing->setHeight(36);
    $drawing->setCoordinates('B15');
    $drawing->setWorksheet($spreadsheet->getActiveSheet());
    /* Конец теста */
    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save('..\..\current\somefile.xlsx');

When downloading and opening the resulting file, an excel error pops up (I use excel 2007):
Workbook "somfile.xlsx" found content that could not be read. Try to restore the contents of the book? If you trust the source of this book, click Yes.

After clicking on the "Yes" button, he does not find anything better than to remove the picture:
A file-level check was performed and the file was then restored. Some fragments of the document may have been restored or deleted.
Remote Component: Print Options.
Removed Component: Drawable shape.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aricus, 2019-04-04
@Aricus

If anyone is interested, this "new, improved" plugin failed to add images. But the "outdated" PhpExcel copes with this task perfectly.

P
Pavel Chesnokov, 2019-01-11
@cesnokov

Perhaps you are using slashes in the wrong direction if you work on Windows:
..\img\barcode.gif

B
Boris Cherepanov, 2020-09-04
@xakplant

I wrote an article just about a new lib. An image is inserted into phpspreadsheets like this
TL;DR

$drawing = new Drawing(); // Новый экземпляр
$drawing->setName($name); // Имя картинки
$drawing->setDescription($name); // Описание
$drawing->setPath($img); // Абсолютный путь на сервере к картинке
$drawing->setCoordinates('A'. $i); // Координаты картинки
$drawing->getShadow()->setVisible(true); // Тень если нужно
$drawing->setWorksheet($sheet); // Нужная вкладка
$drawing->setHeight(100); // Высота в пикселях
$drawing->setWidth(100); // Ширина в пикселях

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question