【问题标题】:Add Pictures to comments in PhpSpreadsheet将图片添加到 PhpSpreadsheet 中的评论
【发布时间】:2019-06-25 07:39:27
【问题描述】:

我在 PhpSpreadsheet 中有一条评论,我想为其添加背景图片。 评论是这样创建的:

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

但是文档中没有关于如何添加背景图片的内容。

【问题讨论】:

  • 你能给它一个 CSS 类并以这种方式添加图片吗?
  • 这是一个Excel文件注释,我觉得不能在Excel里面使用CSS

标签: php phpexcel phpspreadsheet


【解决方案1】:

我能够通过(糟糕但有效的)解决方法解决我的问题。 PHPSpreadsheet 似乎(还)无法为评论创建背景图片,也许 PHPSpreadsheet 将来可以做到。

解决方法: PHPSpreadsheet 无法使用背景图像创建评论,但 Powershell 可以。使用以下 Powershell 脚本,您可以将背景图像添加到工作表 1 中 C2 行的注释中。

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

有了这些知识,您就可以在 PHP 中创建动态的 Powershell 脚本:

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

现在我们创建一个 CMD 脚本,调用该 Powershell 脚本:

$call_powershell_script=Array();
$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);

最后我们在 PHP 中调用这个 CMD 脚本:

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

注意: 通常 Powershell 脚本不需要这一行:

Stop-Process -processname powershell*

但如果没有它,PHP 脚本将永远存在。

注意2: 当脚本由 PHP 运行时,我在 Powershell 中收到一个错误,表明我的 Excel 文件无法访问:

使用“1”参数调用“Open”时出现异常:“Microsoft Office Excel 无法访问文件 'C:\MyExcel.xlsx'。可能的原因有多种:文件名或路径不存在。文件正被另一个程序使用。您尝试保存的工作簿与当前打开的工作簿同名。

已找到此错误的解决方案 here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2014-12-15
    • 1970-01-01
    相关资源
    最近更新 更多