Add Pictures to comments in PhpSpreadsheet

梦想与她 提交于 2021-01-29 15:15:33


I have a comment in PhpSpreadsheet and I want to add a backgroundpicture to it. The comment is created like this:

$spreadsheet->getActiveSheet()->getComment($cell)->getText()->createTextRun('Test text');

But there is nothing in the documentation about how to add a backgroundpicture to it.


I was able to solve my issue with a (bad, but working) workaround. It seems that PHPSpreadsheet is not able (yet) to create a backgroundpicture to a comment, maybe PHPSpreadsheet can do it in the future.

Workaround: PHPSpreadsheet is not able to create a comment with backgroundimage, but Powershell is. With the following Powershell script you are adding a background image to a comment in row C2, in worksheet 1.

$excel = new-object -comobject excel.application
$workbook = $"C:\MyExcel.xlsx")
$worksheet = $workbook.worksheets.item(1)
$image = "C:\MyPicture.png"
$worksheet.Range("C2").AddComment(" ")
Stop-Process -processname powershell*

With that knowledge, you are able to create a dynamically Powershell script inside PHP:

$ps_script[]='$excel = new-object -comobject excel.application';
$ps_script[]='$workbook = $"'.$excel_output_path.'")';
$ps_script[]='$worksheet = $workbook.worksheets.item('.($sheetindex+1).')';
$ps_script[]='$image = "'.$img_path.'"';
$ps_script[]='$worksheet.Range("'.$cell.'").AddComment(" ")';
$ps_script[]='Stop-Process -processname powershell*';
$ps_script = implode("\r\n", $ps_script);
file_put_contents($powershell_output, $ps_script);

Now we create a CMD script, calling that Powershell script:

$call_powershell_script[]="TASKKILL /F /IM powershell.exe";
$call_powershell_script[]="TASKKILL /F /IM EXCEL.exe";
$call_powershell_script[]=$powershell_path.'powershell.exe "'.$powershell_output.'"';
$call_powershell_script[]="TASKKILL /F /IM powershell.exe";
$call_powershell_script[]="TASKKILL /F /IM EXCEL.exe";
$call_powershell_script = implode("\r\n", $call_powershell_script);
file_put_contents($call_powershell_script_path, $call_powershell_script);

And finally we call this CMD script inside PHP:

$output = shell_exec($cpowershell_script_path." 2>&1");
echo "<br>";
echo $output;
echo "<br>";

Note: Normally the Powershell script doesn't need this line:

Stop-Process -processname powershell*

But without it, the PHP script takes forever.

Note2: I received an error in Powershell, when the script was run by PHP, that my Excel file was not accessable:

Exception calling "Open" with "1" argument(s): "Microsoft Office Excel cannot access the file 'C:\MyExcel.xlsx'. There are several possible reasons: The file name or path does not exist. The file is being used by another program. The workbook you are trying to save has the same name as a currently open workbook.

The solution for this error was found here.