1、加载依赖包
composer require phpoffice/phpword
2、官网手册和example
3、体验地址
4、直接导出到本地或者保存word到项目目录
/**
* @param Request $request
* @author: Jackhhy <jackhhy520@qq.com>
* @name: wordexport
* @describe:
*/
public function wordexport(Request $request){
//整体接收的字符串
$str=$request->param("str");
$phpWord = new PhpWord();
//调整页面样式
$sectionStyle = array('orientation' => null,
'marginLeft' => 400,
'marginRight' => 400,
'marginTop' => 400,
'marginBottom' => 400);
$section = $phpWord->addSection($sectionStyle);
//添加页眉
$header=$section->addHeader();
$k=$header->addTextRun();
$k->addImage(ROOT_PATH.'public'.DS."scirobot/home/images/head.jpg",array(
'width' => '100%',
'height' => 60,
'marginTop' => -1,
'marginLeft' => 1,
'wrappingStyle' => 'behind',
));
$section->addTextBreak(2);
//添加页脚
$footer = $section->addFooter();
$f=$footer->addTextRun();
$f->addImage(ROOT_PATH.'public'.DS."scirobot/home/images/foot.jpg",array(
'width' => 580,
'height' => 140,
'marginTop' => -1,
'marginLeft' => 1,
'wrappingStyle' => 'behind',
));
//添加页脚页码
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.',array('align'=>'center'));
$section->addText(
self::$user_info['nickname']." 的写作记录,时间:".date("Y-m-d",time()),
array('name' => '黑体', 'size' => 15),
array('align'=>'center')
);
//添加换行符
$section->addTextBreak(2);
//添加文本,处理文本
$strs=explode(").",$str);
$arr=array_filter($strs);
foreach ($arr as $k=>$v){
$section->addText(
$v.").",
array('name' => 'Arial', 'size' => 13),
array('lineHeight'=>1.5,'indent'=>1)
);
$section->addTextBreak(1); //添加换行
}
$tk=parent::makeToken();
$name="write_".$tk.".docx";
$phpWord->save($name,"Word2007",true);
exit();
/*
//保存到项目目录
$objwrite = IOFactory::createWriter($phpWord);
$k = parent::makeToken();
$t = date("Ymd", time());
$pk = md5($t.$k);//
$dir = iconv("UTF-8", "GBK", ROOT_PATH.'public'.DS.'uploads'.DS."save/".$t);
if (!file_exists($dir)) {
@mkdir($dir, 0777, true);
}
$pa = "save/".$t."/".$pk.".docx";
$objwrite->save(ROOT_PATH.'public'.DS.'uploads'.DS.$pa);
$this->success("", '', 'http://xxxxx/public/uploads/'.$pa);*/
}