需求描述:業(yè)務(wù)方給了個(gè)word模板椒舵,需要我們查出來(lái)數(shù)據(jù)填充進(jìn)去类垦,并且導(dǎo)出為word文件。部分地方需要循環(huán)多行展示政鼠。
準(zhǔn)備工作:
composer require phpoffice/phpword
拉取phpWord擴(kuò)展
代碼:
//加載模板word所需的類
use PhpOffice\PhpWord\TemplateProcessor;
//加載模板文件
public function export(){
$template = new TemplateProcessor(ROOT_PATH . '/demo.docx');
//查出需要展示的數(shù)據(jù)
$data = ['date'=>'2022-11-08','number'=>123];
$template->setValues($data);
//查出需要循環(huán)的數(shù)據(jù)
$each_data = [
['goods_no'=>123,'description_en'=>'a'],
['goods_no'=>234,'description_en'=>'b']
] ;
$template->cloneRowAndSetValues('goods_no', $each_data);
//文件命名并保存到本地
$file_name = "test.docx";
$saveDir= $path = ROOT_PATH . '/';
if (!file_exists($saveDir)) {
mkdir($saveDir, 0777, true);
}
$filepath = $saveDir.'/'.$file_name;
$template->saveAs($filepath);
//輸出到瀏覽器下載
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
}
注意事項(xiàng):
1:模板變量的命名規(guī)則是$符號(hào)加上一個(gè)大括號(hào),然后變量名寫在里面队魏。例如${date}公般。
2:循環(huán)是基于首行的key來(lái)實(shí)現(xiàn)的。