使用phpword插件实现word文档导出

一:安装phpword插件

composer require phpoffice/phpword

phpword的GitHub地址: https://github.com/PHPOffice/PHPWord

phpword文档地址: https://phpword.readthedocs.io/en/latest/

二:phpword使用

phpword的使用十分简单,根据github的教程即可实现,这里我来讲解一下生成word文档的两种方式

1:使用html模板生成word文档

//html模板信息
$html = '<div>111</div>'
$phpWord = new PhpWord();
$section = $phpWord->addSection();
\\PhpOffice\\PhpWord\\Shared\\Html::addHtml($section, $html, false, false);
$objWriter = \\PhpOffice\\PhpWord\\IOFactory::createWriter($phpWord, 'Word2007');
$filename = 'test.docx';
$objWriter->save($filename);

如上就可以将html模板信息生成word文档,如果你想要实现下载word文档

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;filename="' . $title . '.docx"');
header('Cache-Control: max-age=0');
//html信息
$html = '<div>111</div>'
$phpWord = new PhpWord();
$section = $phpWord->addSection();
\\PhpOffice\\PhpWord\\Shared\\Html::addHtml($section, $html, false, false);
$objWriter = \\PhpOffice\\PhpWord\\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('php://output');

2:使用word模板生成word文档

(1)加载word模板

$templateProcessor = new TemplateProcessor('test.docx');

(2)给word模板变量赋值

如给定一个模板:

模板信息为:${name}
用户:${username}

给上面的模板的name和username变量赋值

$templateProcessor->setValue('name', 'word模板');
$templateProcessor->setValue('username', 'test');

我们还可以同时给多个变量同时赋值

$templateProcessor->setValues([
            'name' => ''word模板,
            'username' => 'test',
        ]);

(3):给变量赋值图像

如果想要将变量赋值为图片,可以使用setImageValue方法来设置图像

$templateProcessor->setImageValue('img', 'logo.png');

我们还可以给图像设置样式

$templateProcessor->setImageValue('img', [
'path' => 'logo.png',
'width' => 100,
'height' => 100,
'ratio' => false
]);

(3)给模板循环数次

word模板如下:

${block\_name}
Customer: ${customer\_name}
Address: ${customer\_address}
${/block\_name}

循环并赋值方法如下:

$replacements = array(
    array('customer_name' => 'Batman', 'customer_address' => 'Gotham City'),
    array('customer_name' => 'Superman', 'customer_address' => 'Metropolis'),
);
$templateProcessor->cloneBlock('block_name', 0, true, false, $replacements);

这时候生成的结果如下:

Customer: Batman
Address: Gotham City
  
Customer: Superman
Address: Metropolis

(4)给word模板克隆表格行

word表格模板如下:

| ${userId} | ${userName}    |

|           |----------------+

|           | ${userAddress} |

实现如下:

$values = [
    ['userId' => 1, 'userName' => 'Batman', 'userAddress' => 'Gotham City'],
    ['userId' => 2, 'userName' => 'Superman', 'userAddress' => 'Metropolis'],
];
$templateProcessor->cloneRowAndSetValues('userId', $values);

生成的结果如下:

| 1 | Batman      |

|    |------------+

|    | Gotham City|

| 2 | Superman    |

|   |-------------+

|   | Metropolis  |

(5)生成word文档并保存,使用saveAs方法实现

$templateProcessor->saveAs('test.docx');

根据如上就可以实现word模板生成word文档

猜你喜欢

转载自blog.csdn.net/qq_39436397/article/details/104439159