首先使用composer安装PHPWord
composer require phpoffice/phpword
创建一个公共方法
function exportWorld()
{
$phpWord = new PhpWord();//实例化对象
$section = $phpWord-addSection();//新增一个空白页
$section-addText('hello');//添加一个段落文字
$textrun = $section-addTextRun();//普通文字,一个段落,可以在后面追加文字
$textrun-addText('world');//在上面的文字后面添加文字
$textrun-addTextBreak(1);//文字换行,参数表示几行
$section-addTextBreak(1);//段落直接换行
$section-addPageBreak();//添加换行符
//字体样式
$fstyle = [
? 'name' ='宋体',? //字体
? 'color'= 'red',? //颜色
? 'bold' = true'? //加粗
];
//段落样式
$pstyle = [
? 'align' ='center',? //对齐方式
$section-addText('how are you!',$fstyle,$pstyle);//添加自定义文字样式和段落样式的
header('pragma:public');
header("Content-Disposition:attachmeng;filename=hello.doc");//设置导出保存的文件名
$objWriter-save('php://output');
}
以下举例一些常用的参数配置
设置文档属性
$pro = $PHPWord-getProperties();
$pro-setCreator('Jankin');? ? ? ? //创建者
$pro-setCompany('apple');? ? ? ? //公司
$pro-setTitle('computer science');? ? ? ? //标题
$pro-setDescription('this is computer science document.');//描述
$pro-setCategory('computer');? ? ? //分类
$pro-setLastModifiedBy('Jankin');? ? //最后修改者
$pro-setSubject('computer science');//主题
$pro-setKeywords('science');//关键词
设置常用页面样式
$pStyle = [
? 'orientation' = null,//页面方向,默认null是竖向,landscape是横向
? 'borderTopColor' = 'red',//上边框颜色
? 'borderLeftColor' = 'red',//左边框颜色
? 'borderRightColor' = 'red',//右边框颜色
? 'borderBottomColor' = 'red',//下边框颜色
设置常用文本样式
? 'name' = '宋体',//字体名称
? 'bold' = true,//加粗
? 'italic' = true,//斜体
? 'Color' = 'red',//颜色
原文链接 PHPWord导出Word
$this-assign(别名', $this-model-getall($id));
ob_start();
header("Content-type:application/octet-steam");
//可以请求网页实体的一个或者多个子范围字段
header("Accept-Ranges:bytes");
//将查询结果导出到word
header("Content-type:application/vnd.ms-excel");
//把请求所得的内容存为一个文件的时候提供一个默认的文件名
header("Content-Disposition:filename=名称-" . date("YmdHis") . ".doc");
//清除缓冲区内容
ob_end_flush();
如果没有图片要导出的话,可以使用以下简单方式.
php
header("Content-type:application/vnd.ms-word");
header("Content-Disposition:filename=zgfun.doc");
echo
"要导出的内容一.\r\n";
"要导出的第二行.";
=============
以上就是土嘎嘎小编为大家整理的php数据导出成word相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!