Dreanmwear能做php模板吗,PHPword模板的使用
最近手上的項目需要生成word文檔并保存下來,網上搜索了一下找到了PHPword,記錄一下,免得以后再用到又去百度一大堆。
項目使用的是thinkPHP5.1框架。
composer安裝phpword擴展,cmd切換路徑到項目根目錄下輸入
composer require phpoffice/phpword
安裝完成后控制器中引入phpword
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
然后去創建一個word文檔用作模板,盡量用office2007(.docx后綴)吧(PS:網上看到phpword對doc的支持不太友好,容易替換失敗)。
把word文檔的格式都設置好,然后在需要替換內容的地方添加替換標簽,模板標簽格式為${標簽名}如圖:
準備工作就緒,開始寫代碼
public function create_word(){
$phpWord = new PhpWord;
//打開模板
$template = $phpWord->loadTemplate('public/static/doc/template1.docx');
//模板替換
$template->setValue('name', '小明');
$template->setValue('sex', '男');
$template->setValue('phone_number', '18888888888');
$template->setValue('email', '18888888888@163.com');
$template->setValue('school', 'XXX大學');
$template->setValue('edu', '本科');
//輸出換行到word文檔用
$template->setValue('expertise', '1.PHP
2.mysql
3.linux');
$template->setValue('job', 'PHP工程師、全棧工程師、架構師');
//文件命名
$fileName = md5(rand(1000, 9999)).'.docx';
//文件保存路徑
$filePath = 'public/static/create/'.$fileName;
//保存文件
$template->saveAs($filePath);
}
調用這個方法
保存為word文檔
查看效果
至此,簡單的模板替換就完成了,再加個下載
public function create_word(){
$phpWord = new PhpWord;
//打開模板
$template = $phpWord->loadTemplate('public/static/doc/template1.docx');
//模板替換
$template->setValue('name', '小明');
$template->setValue('sex', '男');
$template->setValue('phone_number', '18888888888');
$template->setValue('email', '18888888888@163.com');
$template->setValue('school', 'XXX大學');
$template->setValue('edu', '本科');
//輸出換行到word文檔用
$template->setValue('expertise', '1.PHP
2.mysql
3.linux');
$template->setValue('job', 'PHP工程師、全棧工程師、架構師');
//文件命名
$fileName = md5(rand(1000, 9999)).'.docx';
//文件保存路徑
$filePath = 'public/static/create/'.$fileName;
//保存文件
$template->saveAs($filePath);
ob_clean();
if(!is_file($filePath) || !is_readable($filePath)) exit('未找到文件');
$fileHandle = fopen($filePath,"rb");
if($fileHandle === false) exit("文件讀取失敗");
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
header("Content-Length: ".filesize($filePath));
header('Content-Disposition:attachment;fileName="'.urlencode($fileName).'"');
while(!feof($fileHandle)) {
echo fread($fileHandle, 10240);
}
fclose($fileHandle);
}
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Dreanmwear能做php模板吗,PHPword模板的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么用u盘装系统启动不了怎么办 u盘装
- 下一篇: 华硕笔记本怎么使用 华硕笔记本使用方法大