这篇文章主要讲解如何在php环境下使用phpword在文档中插入表格的功能。
首先,先避个坑,phpword版本为0.18.3,其他版本在插入table后,生成的word无法打开,报错:
Xml parsing error
位置:部分:/word/document.xml 行:0,列:0
。。。。
废话不多说,先上干货,打包好的代码已经贴到文章最后了,按下面说的无法部署的直接扒源码放到系统里。
来看代码:
如果你本机没安装composer的话,先去官网下载一个。
然后找到
点击安装后,重开cmd即可。
这个phpword需要composer安装
composer require phpoffice/phpword
安装完成后,在你的项目根目录,打开cmd,输入上面命令,则会自动安装
安装完成后,在项目根目录则会出现以下文件。
下面新建php文件,来实现调用方法
<?php
include_once "vendor/autoload.php";
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
$PHPWord = new PhpWord();
$section = $PHPWord->createSection();
$PHPWord->addTitleStyle(1, array('bold' => true, 'size' => 18, 'name' => 'Arial', 'Color' => '333'), array('align' => 'center'));
$section->addTitle("hello world", 1);
//定义样式数组
$styleTable = array(
'borderSize'=>6,
'borderColor'=>'000000',
'cellMargin'=>150
);
$styleFirstRow = array(
'borderBottomSize'=>18,
'borderBottomColor'=>'000000',
'bgColor'=>'66bbff'
);
$cellStyle = array('gridSpan' => 2);
//添加表格样式
$PHPWord->addTableStyle('myOwnTableStyle',$styleTable,$styleFirstRow);
//添加表格
$table = $section->addTable('myOwnTableStyle');
$table->addRow();
$table->addCell(3000)->addText('测试1');
$table->addCell(3000)->addText('测试2');
$table->addCell(3000)->addText('测试3');
$table->addRow();
$table->addCell(3000)->addText('测试4');
$table->addCell(6000,$cellStyle)->addText('测试5'); //合并行单元格
$table->addRow();
$table->addCell(3000,array('vMerge' => 'restart'))->addText('合并');
$table->addCell(3000)->addText('测试6');
$table->addCell(3000)->addText('测试7');
$table->addRow();
$table->addCell(3000,array('vMerge' => 'continue'));
$table->addCell(3000)->addText('测试8');
$table->addCell(3000)->addText('测试9');
$table->addRow();
$table->addCell(3000)->addText('测试10');
$table->addCell(3000)->addText('测试11');
$table->addCell(3000)->addText('测试12');
$file = '测试.docx';
//文档存在服务器上用此代码
// $objWriter = IOFactory::createWriter($PHPWord, 'Word2007');
// $objWriter->save('123.docx');
//直接下载不存储在服务器上用此代码
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = IOFactory::createWriter($PHPWord, 'Word2007');
$xmlWriter->save("php://output");
?>
也不难,第一步include_once引入composer,然后定义命名空间,后面实例化phpword(),然后操作表格,合并单元格的方式为:
$table->addCell(6000,$cellStyle)->addText('测试5'); //合并行单元格
$table->addCell(3000,array('vMerge' => 'restart'))->addText('合并');//合并列单元格
如果有很多列,则第一列的vMerge为restart,下面列为continue,然后后面不用指定内容。
$table->addCell(3000,array('vMerge' => 'continue'));//合并列单元格
。。。
完成后,会生成如下格式的word
文末附件地址: