gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:46:47 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com