项目需要导出word报告,而且需要在word中绘制表格,并且表格有跨行跨列设置,相关参考文档并不多,自己就看了一下源码结合 官方文档 实现跨行跨列效果,做个简单记录
简单来说跨列colspan使用gridSpan属性:int,跨列使用vMerge属性:restart/continue 示例代码如下
$baseCellStyle = ['borderSize'=>1,'vAlign'=>VerticalJc::CENTER,'vMerge'=>'restart'];//基础单元格属性,建议vMerge设置为restart,应该是重新开始一行的意思
$colspan4 = array_merge(['gridSpan'=>4],$baseCellStyle);//跨4列单元格
$colspan3 = array_merge(['gridSpan'=>3],$baseCellStyle);//跨3列单元格
$colspan2 = array_merge(['gridSpan'=>2],$baseCellStyle);//跨2列单元格
$rowSpan = array_merge($baseCellStyle,['vMerge'=>'continue']);//跨行单元格,注意与跨列设置数量不同
$baseFontStyle = ['size'=>10,'lineHeight'=>1];
$boldFontStyle = array_merge(['bold'=>true],$baseFontStyle);
$titleFontStyle = ['size'=>12,'bold'=>true];
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText("联网工业企业定级信息",$titleFontStyle);
$section->addTextBreak();
$table = $section->addTable();
$table->addRow();
$table->addCell(2500,$baseCellStyle)->addText('定级要素',$boldFontStyle);//2500是宽度,没完全弄懂宽度的意思,请自行尝试
$table->addCell(5000,$colspan2)->addText('要素信息',$boldFontStyle);//跨两列
$table->addCell(2500,$baseCellStyle)->addText('自主打分',$boldFontStyle);
$table->addRow();
$table->addCell(2500,$baseCellStyle)->addText('定级要素一:企业所在行业网络安全影响程度(20分)',$boldFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('企业所属行业',$boldFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('',$baseFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('',$baseFontStyle);
$table->addRow();
$table->addCell(2500,$baseCellStyle)->addText('定级要素二:企业规模(20分)',$boldFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('企业规模',$boldFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('',$baseFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('',$baseFontStyle);
$table->addRow();
$table->addCell(2500,$rowSpan);//跨行,与上一行合并
$table->addCell(2500,$baseCellStyle)->addText('从业人员数',$boldFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('',$baseFontStyle);
$table->addCell(2500,$rowSpan);跨行,与上一行合并
$table->addRow();
$table->addCell(2500,$rowSpan);//跨行,与上一行合并
$table->addCell(2500,$baseCellStyle)->addText('营业收入',$boldFontStyle);
$table->addCell(2500,$baseCellStyle)->addText('',$baseFontStyle);
$table->addCell(2500,$rowSpan);//跨行,与上一行合并
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save('test.docx');
具体效果如下