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

时间:2016-12-23 06:24:06

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

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

template.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}

4 个答案:

答案 0 :(得分:5)

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

运作良好。仍然试图想出如何将其保存为新文件并强行下载。

答案 1 :(得分:1)

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

composer require phpoffice/phpword 

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

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');

<强>更新
您可以将限制作为第三个参数传递给$template->setValue($search, $replace, $limit),以指定应该进行多少次匹配。

答案 2 :(得分:1)

我有同样的任务来编辑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();
    }

答案 3 :(得分:0)

如果您找到简单的解决方案,可以使用此library

实施例: 此代码将$ search替换为$ pathToDocx文件中的$ replace

$docx = new IRebega\DocxReplacer($pathToDocx);

$docx->replaceText($search, $replace);
相关问题