?1.安裝phpword包composer require phpoffice/phpword
2.模板文件結構
如上圖框住的是要替換的文本和要復制表格樣式
實現代碼
<?phpnamespace app\api\logic;use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\SimpleType\TblWidth;
use PhpOffice\PhpWord\TemplateProcessor;
class Word
{public static function test($arr,$title,$stu_name){//多行數據參考<w:br/>用于換行
// $arr = [
// ['id' => '1', 'value' => '單詞內容<w:br/>單詞內容<w:br/>單詞內容單詞內容單詞內容單<w:br/>詞內容單詞內容單詞內容單詞內容單詞內容單<w:br/>詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容單詞內容'],
// ['id' => '2', 'value' => '單詞內容單詞內容單詞內<w:br/>容單詞內容單詞內容'],
// ['id' => '3', 'value' => '單詞內容單詞<w:br/>內容單詞內容單詞內容單詞內容'],
// ['id' => '4', 'value' => '單詞內容單詞內容單<w:br/>詞內容單詞內容單詞內容單詞內容單詞內容單<w:br/>詞內容單詞內容單詞內容<w:br/>單詞內容單詞內容單詞內容單詞內容單詞內容'],
// ['id' => '5', 'value' => '單<w:br/>詞<w:br/>內<w:br/>容'],
// ];//新文件名$filename = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).".docx";$date = date('Y-m-d');$path = "export/word/$date/";if (!file_exists($path)) {mkdir($path, 0777, true);}//實例化, 參數傳入模板文件地址$word_template = ROOT_PATH.'public/export/test.docx'; // 使用絕對路徑// 檢查模板文件是否存在if (!file_exists($word_template)) {throw new \Exception("模板文件不存在: " . $word_template);}$templateProcessor = new TemplateProcessor($word_template);//替換(設置)變量值$array_title = ['title' => $title,'date' => $date,'num' => count($arr),'name' => $stu_name,];$templateProcessor->setValues($array_title);//生成表格$table = new Table(['borderSize' => 12, 'width' => 6000, 'unit' => TblWidth::TWIP, 'alignMent' => 'center']);$rows = count($arr);//總行數$templateProcessor->cloneRow('id', $rows);//$arr條數復制行for ($i = 0; $i < $rows; $i++) {$templateProcessor->setValue("id#" . ($i + 1), $arr[$i]['id']);//替換變量$templateProcessor->setValue("value#" . ($i + 1), $arr[$i]['value']);//替換變量}$templateProcessor->setComplexBlock('table', $table);//保存文件$templateProcessor->saveAs($path . $filename);return "/" . $path . $filename;}}
上圖是最終生成的word文件