php - 读取和替换 .docx (Word) 文件中的内容

标签 php laravel ms-word laravel-5.3 docx

我需要根据用户输入替换一些word文档中的内容。我正在尝试读取模板文件(例如“template.docx”),并替换名字 {fname}、地址 {address} 等。

模板.docx:

To,
The Office,
{officeaddress}
Sub:  Authorization Letter
Sir / Madam,

I/We hereby authorize  to  {Ename}  whose signature is attested here below, to submit application and collect Residential permit for {name}  
Kindly allow him to support our International assignee

{name}                                          {Ename}  

有没有办法在 Laravel 5.3 中做同样的事情?

我正在尝试使用 phpword,但我只能看到编写新 word 文件的代码 - 但不能读取和替换现有文件。另外,当我只是简单地读写时,格式就乱七八糟了。

代码:

$file = public_path('template.docx');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);

$phpWord->save('b.docx');

b.docx

To,
The Office,
{officeaddress}

Sub: 
 Authorization Letter
Sir / Madam,


I/We hereby authorize 
 to

{Ename}


whose signature is attested here below, to submit a
pplication and collect Residential permit
 for 
{name}

Kindly allow him to support our International assignee


{name}













{
E
name}

最佳答案

这是@addweb-solution-pvt-ltd 的回答的工作版本。

//This is the main document in  Template.docx file.
$file = public_path('template.docx');

$phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);

$phpword->setValue('{name}','Santosh');
$phpword->setValue('{lastname}','Achari');
$phpword->setValue('{officeAddress}','Yahoo');

$phpword->saveAs('edited.docx');

但是,并不是所有的 {name} 字段都在变化。不知道为什么。


或者:

// Creating the new document...
$zip = new \PhpOffice\PhpWord\Shared\ZipArchive();

//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';

$file = public_path('template.docx');
$temp_file = storage_path('/app/'.date('Ymdhis').'.docx');
copy($template,$temp_file);

if ($zip->open($temp_file) === TRUE) {
    //Read contents into memory
    $oldContents = $zip->getFromName($fileToModify);

    echo $oldContents;

    //Modify contents:
    $newContents = str_replace('{officeaddqress}', 'Yahoo \n World', $oldContents);
    $newContents = str_replace('{name}', 'Santosh Achari', $newContents);

    //Delete the old...
    $zip->deleteName($fileToModify);
    //Write the new...
    $zip->addFromString($fileToModify, $newContents);
    //And write back to the filesystem.
    $return =$zip->close();
    If ($return==TRUE){
        echo "Success!";
    }
} else {
    echo 'failed';
}

效果很好。仍在尝试弄清楚如何将其另存为新文件并强制下载。

关于php - 读取和替换 .docx (Word) 文件中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296206/

相关文章:

c# - 如何在 C# 中创建 Word 文档?

php - 替换字符串中偶数位置的所有字符的最简单方法。

php - 理解为什么 echo 在 php 类函数中不起作用

javascript - AngularJS http.jsonp 请求 .then 和 .success 函数不起作用

javascript - vue v-for 图像未显示。相反,它显示字符串

Delphi Ms word自动化页面在Windows 10中设置和保存

php - 英镑和便士的定价问题!

php - 显示来自站点根目录之外的图像

html - Font Awesome 图标与 laravel 5 形式

java - 使用带有绝对定位框的 Python 或 Java 生成 DOC(和 DOCX)模板