demo


日期${date}单号${number}
商品单号${goods}商品名称${description_en}








需求描述:如上图,业务方给了个word模板,需要我们查出来数据填充进去,并且导出为word文件。部分地方需要循环多行展示。

准备工作:

composer require phpoffice/phpword
拉取phpWord扩展

代码:

//加载模板word所需的类
use PhpOffice\PhpWord\TemplateProcessor;

//加载模板文件
public function export(){
$template = new TemplateProcessor(ROOT_PATH . '/demo.docx');
//查出需要展示的数据
$data = ['date'=>'2022-11-08','number'=>123];
$template->setValues($data);
//查出需要循环的数据
$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);

}


返回
顶部