以下 PHP 代码非常适用于 word 文档(特别是 .docx),但对于 excel (.xlsx),它不会更改占位符。据我了解,此代码将 word 文件转换为 document.xml 文件,并在 zip 文件的 word 文件夹中找到 {{placeholder}} 并将其更改为我们想要的文本。
if(isset($_POST["e_submit"]))
{
$name=(string) $_POST["e_name"];
$email=(string) $_POST["e_email"];
$source='TemplateSimpleText.docx';
$temp='template'.'.docx';
copy($source,$temp);
$zip = new ZipArchive;
$fileXml='word/document.xml';
if($zip->open($temp) === TRUE)
{
$old=$zip->getFromName($fileXml);
$new=str_replace('{{Name}}',$name,$old);
$new=str_replace('{{Email}}',$email,$new);
$zip->deleteName($fileXml);
$zip->addFromString($fileXml,$new);
$zip->close();
if (ob_get_level()) {
ob_end_clean();
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($temp));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($temp));
readfile($temp);
unlink($temp);
exit();
}
}
最佳答案
对于 Excel 文档,您必须编辑几个不同的文件。即:
xl/sharedStrings.xml
字符串 xl/worksheets/sheet1.xml
(和其他 sheet#.xml
)用于数值 xl/workbook.xml
在需要时强制重新计算 工作代码:
$zip = new ZipArchive;
if ($zip->open($tmp_file) === true) {
$xml = 'xl/sharedStrings.xml';
$old_contents = $zip->getFromName($xml);
$new_contents = strtr($old_contents, [ 'old' => 'new' ]);
$zip->deleteName($xml);
$zip->addFromString($xml, $new_contents);
$xml = 'xl/worksheets/sheet1.xml';
$old_contents = $zip->getFromName($xml);
$new_contents = strtr($old_contents, [ '123' => '456' ]);
$zip->deleteName($xml);
$zip->addFromString($xml, $new_contents);
$xml = 'xl/workbook.xml';
$old_contents = $zip->getFromName($xml);
$new_contents = strtr($old_contents, [
'<calcPr' => '<calcPr fullCalcOnLoad="1" ',
]);
$zip->deleteName($xml);
$zip->addFromString($xml, $new_contents);
$zip->close();
/* ... do something with your zip file ... */
}
强制重新计算 仅在电子表格 编辑器 中有效。他们在 xlsx viewers 中做 而不是 工作。
关于php - 如何使用 str_replace() 函数从 php 中的 excel 文件中替换占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44590031/