准备将合同招标文件管理程序从C/S迁移到B/S,后台打算使用PHP来完成,主要的技术点之一是PHP对WORD文件的操作,比如操作Word的书签,或者指定模板文件来替换里面的内容,早上就在网上寻找可以操作的类库。
今天比较顺利,找了两个类库都可以,不需要安装,直接拷贝到具体的目录下即可使用,但是第一个只是安装mht方式来生成文件,然后存储为Word文件,不符合我的要求。
第二个则是指定替换的格式,比如template.docx文件内有
${name}${city}${Street}
则下面的代码将替换其中的内容
<?php
require_once 'bootstrap.php';
//$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('Template.docx');
$templateProcessor->setValue('name', '这个是替换后的内容');
$templateProcessor->setValue(array('City', 'Street'), array('Detroit', '12th Street'));
$templateProcessor->saveAs('Sample_07_TemplateCloneRow.docx');
?>
程序执行后自动替换相应的内容,当然,你也可以按自己的方式来指定替换样式。
下面的代码将生成Word文件并下载到客户端:
<?php
require_once 'bootstrap.php';
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->createSection();
$section->addText('Hello World!');
$file = 'HelloWorld.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("http://127.0.0.1/HTAPP/PHPOffice/");
?>
为这些生产高质量代码(基础类库)的作者点赞,他们是真正的无名英雄!我们都是站在他们的肩膀上来做事情了。
我将该类库已经上传了,要使用的请下载。