【问题标题】:Read and replace contents in .docx (Word) file读取和替换 .docx (Word) 文件中的内容
【发布时间】:2016-12-23 06:24:05
【问题描述】:

我需要根据用户输入替换一些 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}

【问题讨论】:

标签: php laravel ms-word laravel-5.3 docx


【解决方案1】:

这是@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';
}

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

【讨论】:

  • 查看我的更新以了解您的解决方案
【解决方案2】:

要读取和替换 Doc 文件中的内容,您可以使用 PHPWord 包并使用 composer 命令下载此包:

composer require phpoffice/phpword 

根据version v0.12.1,您需要从src/PHPWord 文件夹中获取PHP Word Autoloader.php 并注册它

require_once 'src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();

1) 打开文档

$template = new \PhpOffice\PhpWord\TemplateProcessor('YOURDOCPATH');

2) 替换单个字符串变量

$template->setValue('variableName', 'MyVariableValue');

3) 替换多次出现的字符串变量
- 将您的数组占位符克隆到您的数组计数

$template->cloneRow('arrayName', count($array));  

- 替换变量值

for($number = 0; $number < count($array); $number++) {
    $template->setValue('arrayName#'.($number+1), htmlspecialchars($array[$number], ENT_COMPAT, 'UTF-8'));
}

4) 保存更改的文档

$template->saveAs('PATHTOUPDATED.docx');

更新
您可以将 limit 作为第三个参数传递给 $template-&gt;setValue($search, $replace, $limit) 以指定应该发生多少匹配。

【讨论】:

  • setValue(),并不总是有效。格式化有区别吗?文档还提到了宏中的变量。
  • AddWeb 的解决方案根本不起作用。没有错误,但模板被保存为一个新文档,完全没有变化。相反,我使用了带有 str_replace 的@SantoshAchari 解决方案。尽管如此,仍有一些占位符没有被替换。仍在检查原因。
  • @DvdEnde 它似乎高度依赖于 Microsoft Word 的版本。就我而言,它处理了 PHPWord 中的示例 word 文档,这似乎是 word 2003。
【解决方案3】:

我有同样的任务在 php 中编辑 .doc.docx 文件,我已经使用了这个代码。

参考http://www.onlinecode.org/update-docx-file-using-php/

    $full_path = 'template.docx';
    //Copy the Template file to the Result Directory
    copy($template_file_name, $full_path);

    // add calss Zip Archive
    $zip_val = new ZipArchive;

    //Docx file is nothing but a zip file. Open this Zip File
    if($zip_val->open($full_path) == true)
    {
        // In the Open XML Wordprocessing format content is stored.
        // In the document.xml file located in the word directory.

        $key_file_name = 'word/document.xml';
        $message = $zip_val->getFromName($key_file_name);               

        $timestamp = date('d-M-Y H:i:s');

        // this data Replace the placeholders with actual values
        $message = str_replace("{officeaddress}", "onlinecode org", $message);
        $message = str_replace("{Ename}", "ingo@onlinecode.org", $message); 
        $message = str_replace("{name}", "www.onlinecode.org", $message);   

        //Replace the content with the new content created above.
        $zip_val->addFromString($key_file_name, $message);
        $zip_val->close();
    }

【讨论】:

    【解决方案4】:

    如果你找到简单的解决方案,你可以使用这个library

    示例: 此代码将在 $pathToDocx 文件中将 $search 替换为 $replace

    $docx = new IRebega\DocxReplacer($pathToDocx);
    
    $docx->replaceText($search, $replace);
    

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多