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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41296206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:59:28  来源:igfitidea点击:

Read and replace contents in .docx (Word) file

phplaravelms-wordlaravel-5.3docx

提问by Santosh Achari

I need to replace content in some word documents based on User input. I am trying to read a template file (e.g. "template.docx"), and replace First name {fname}, Address {address} etc.

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

template.docx:

模板.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}  

Is there a way to do the same in Laravel 5.3?

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

I am trying to do with phpword, but I can only see code to write new word files - but not read and replace existing ones. Also, when I simply read and write, the formatting is messed up.

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

Code:

代码:

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

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

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}

回答by Santosh Achari

This is the working version to @addweb-solution-pvt-ltd 's answer.

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

However, not all of the {name} fields are changing. Not sure why.

但是,并非所有 {name} 字段都在更改。不知道为什么。



Alternatively:

或者:

// 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';
}

Works well. Still trying to figure how to save it as a new file and force a download.

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

回答by JON

I have same task to edit .docor .docxfile in php, i have use this code for it.

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

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

参考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}", "[email protected]", $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();
    }

回答by AddWeb Solution Pvt Ltd

To read and replace content from Doc file, you can use PHPWordpackage and download this package using composercommand:

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

composer require phpoffice/phpword 

As per version v0.12.1, you need to require the PHP Word Autoloader.phpfrom src/PHPWordfolder and register it

根据v0.12.1 版本,您需要Autoloader.phpsrc/PHPWord文件夹中获取 PHP Word并注册它

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

1) Open document

1) 打开文档

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

2) Replace string variables for single

2) 替换单个字符串变量

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

3) Replace string variables for multi occurrence
- Clone your array placeholder to the count of your array

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

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

- Replace variable value

- 替换变量值

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

4) Save the changed document

4) 保存更改的文档

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

UPDATE
You can pass limit as third parameter into $template->setValue($search, $replace, $limit)to specifies how many matches should take place.

UPDATE
您可以将 limit 作为第三个参数传递$template->setValue($search, $replace, $limit)到指定应该进行多少匹配。

回答by Igor Rebega

If you find simple solution you can use this library

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

Example: This code will replace $search to $replace in $pathToDocx file

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

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

$docx->replaceText($search, $replace);