PHPWORD使用檔案
一:引入
tp5.0,tp5.1:
1:composer方式(推薦)
a:根目錄下執行:composer require phpoffice/phpword
b:引入:
use PhpOffice\PhpWord\PhpWord;
2:下載引入方式
a:下載PHPWord:
地址:https://pan.baidu.com/s/19UctPmT5tdn0SqrEgM56MA
提取碼:zxcv
b:放到專案根目錄extend檔案夾下,目錄結構如下:

c:引入
use PhpOffice\PhpWord\PhpWord;
二:匯出
$file = '../extend/files/pdf.docx';//路徑,可更改
$PHPWord = new PhpWord();
$template = $PHPWord->loadTemplate($file);//加載模板
$template->setValue('title', '標題');//替換值
$file = date('Y-m-d-H-i-s') . '.docx';//檔案名
$encoded_filename = urlencode($file); // 將檔案名進行urlencode轉碼
$file = str_replace('+', '%20', $encoded_filename);
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');
$template->saveAs('php://output');
格式:
//替換值(模板內為${title},如模板圖)
$template->setValue('title', '標題');
//選擇框(模板內為check0和check1<字體是【Wingdings 2】>,替換時R是選中,£是未選,如模板圖)
$template->setValue('check0', 1? 'R' : '£');//與模板內check0對應,變數命名可更改,與模板一致即可
$template->setValue('check1', 0? 'R' : '£');//與模板內check1對應,變數命名可更改,與模板一致即可
//復制行
$template->cloneRow('本行最左邊的變數名', '要復制的行數');
//復制行-舉例(如模板圖)
$user = [['no'=>'1', 'name'=>'張三', 'sex'=>'男'], ['no'=>'2', 'name'=>'李四', 'sex'=>'女']];
$rows = count($user);
$template->cloneRow('no', $rows);//復制行,no是要復制行的最左邊變數,$rows代表復制幾行,復制后會是no#1,name#1,sex#1;no#2,name#2,sex#2這樣的
for ($i = 0; $i < $rows; $i++) {
$template->setValue('no#' . ($i + 1), $user[$i]['no']);
$template->setValue('name#' . ($i + 1), $user[$i]['name']);
$template->setValue('sex#' . ($i + 1), $user[$i]['sex']);
}
//復制塊,也可用于是否顯示
$template->cloneBlock('塊標簽名','數量');//模板內為${塊標簽名}和${/塊標簽名}和html標簽一樣,成對出現,內容放中間
//復制塊-舉例(如模板圖)
$show_name="顯示";
$template->cloneBlock('show',2);//復制兩個
$template->setValue('show_name',$show_name);//設定值
$template->cloneBlock('hide',0);//復制0個,代表隱藏,值也不用設了
//插入圖片(模板內為${img})
$template->setImageValue('img', ['path' => '路徑','width'=>500,'height'=>500]);
模板圖
結果圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232289.html
標籤:PHP
下一篇:tp5.1生成二維碼
