PHPSpreadsheet - How do i place a image from link into my excel file?

Pascal picture Pascal · Feb 20, 2019 · Viewed 13.5k times · Source

I would like to place a image in cell a1 from my excel file.

I tryed different things from phpspreadsheet website but all without succes. Like this example from them that does'nt work.:

$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Paid');
$drawing->setDescription('Paid');
$drawing->setPath('https://pngimage.net/wp-content/uploads/2018/06/rfhnbyrb-png-6.png');
$drawing->setCoordinates('B15');
$drawing->setOffsetX(110);
$drawing->setRotation(25);
$drawing->getShadow()->setVisible(true);
$drawing->getShadow()->setDirection(45);

If i create a black bar with text inside it it works with this code.:

$gdImage = @imagecreatetruecolor(2000, 20) or die('Cannot Initialize new GD image stream');
$textColor = imagecolorallocate($gdImage, 255, 255, 5);
imagestring($gdImage, 1, 5, 5, date("F Y"), $textColor);

//  Add the In-Memory image to a worksheet
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
$drawing->setName('In-Memory image 1');
$drawing->setDescription('In-Memory image 1');
$drawing->setCoordinates('A1');
$drawing->setImageResource($gdImage);
$drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG);
$drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setHeight(36);
$drawing->setWorksheet($spreadsheet->getActiveSheet());

what i try i don't get a image in my excel file, please who wants to help me.

Answer

mindmaster picture mindmaster · Feb 20, 2019

I got a solution for you. But unfortunately i couldn't find a way to use a url but an image localy. take a look.

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Paid');
$drawing->setDescription('Paid');
$drawing->setPath('images/paid.png'); // put your path and image here
$drawing->setCoordinates('B15');
$drawing->setOffsetX(110);
$drawing->setRotation(25);
$drawing->getShadow()->setVisible(true);
$drawing->getShadow()->setDirection(45);
$drawing->setWorksheet($spreadsheet->getActiveSheet());

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

It's working just fine, enjoy :)

enter image description here

enter image description here