php-word使用


php-word使用

版本
1
"phpoffice/phpword": "^0.18.3"
代码
1
2
3
4
5
6
7
8
9
10
$phpWord = new PhpWord();
$this->section = $phpWord->addSection();
$this->add('加一行');

//加一个表格
$this->addTable([]);

$objWriter = IOFactory::createWriter($phpWord);
$path = 'xxx.docx';//附件临时存放地址
$objWriter->save($path);
添加行
1
2
3
4
5
6
7
8
9
10
private function add($text = '', $size = 13, $color = '130c0e')
{
$fontStyle = new Font();
$fontStyle->setBold(false);
$fontStyle->setSize($size);
$fontStyle->setPosition(40);
$fontStyle->setColor($color);
$element = $this->section->addText($text);
$element->setFontStyle($fontStyle);
}
添加表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private function addTable($data)
{
$tableStyle = (new Table())
->setBorderColor('006699')
->setBorderSize(6)
->setCellMargin(100)
->setPosition((new TablePosition())->setTblpYSpec(TablePosition::YALIGN_INLINE));

$cellStyle = ['valign' => 'center'];//居中
$table = $this->section->addTable($tableStyle);
$table->addRow(600);//添加一行,高度600
$table->addCell(1000, $cellStyle)->addText('第一列');//添加一列,宽度1000
$table->addCell(2000, $cellStyle)->addText('第二列');//添加一列,宽度2000
$table->addCell(3000, $cellStyle)->addText('第三列');//添加一列,宽度3000
$table->addCell(4000, $cellStyle)->addText('第四列');//添加一列,宽度4000
$table->addCell(1000, $cellStyle)->addText('第五列');//添加一列,宽度1000

foreach ($data as $item) {
$table->addRow(600);
$table->addCell(1000, $cellStyle)->addText('一列循环');
$table->addCell(2000, $cellStyle)->addText('二列循环');
$table->addCell(3000, $cellStyle)->addText('三列循环');
$table->addCell(4000, $cellStyle)->addText('四列循环');
$table->addCell(1000, $cellStyle)->addText('五列循环');
}

$cellColSpan = ['gridSpan' => 4, 'valign' => 'center'];//合并四个单元格并居中

$table->addRow(800);
$table->addCell(10000, $cellColSpan)->addText('合并了四个单元格');
$table->addCell(1000, $cellStyle)->addText('第五列结尾');

}