TP5利用phpforword生成word表格文档

1.首先用composer安装下载 phpoffice/phpforword

composer require phpoffice/phpword

image.png

2.在controller里引用

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

3.生成简单表格代码如下

$PHPWord = new PhpWord();
$section = $PHPWord->createSection();
$PHPWord->addTitleStyle(1, array('bold' => true, 'size' => 18, 'name' => 'Arial', 'Color' => '333'), array('align' => 'center'));
$section->addTitle("编程爱好者之家", 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('存储地址/编程爱好者.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");

生成文档如下图所示

image.png

原文地址:https://www.codelovers.cn/article/20191218110020.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值