日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

Dreanmwear能做php模板吗,PHPword模板的使用

發布時間:2024/10/8 php 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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模板的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。