PHP生成Word文档,ODT文档,RTF文档
源码地址:
https://github.com/PHPOffice/PHPWord
PHP生成Word文档,进过测试暂时只能支持*.docx格式的Word文件
//引入PHPword类
use PhpOffice\PhpWord\Autoloader;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\IOFactory;
require_once 'PhpWord/Autoloader.php';
//实例化PHPword类
$phpWord = new \PhpOffice\PhpWord\PhpWord();
//要附加到Word文档的每个元素被放置在一个部分。
//要创建一个基本的部分:
$section = $phpWord->addSection();
//创建段后,可以追加要素:
$section->addText('Hello world!');
// 您可以通过给addText直接样式的文本功能的数组:
$section-->addText('Hello world! I am formatted.',
array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
//如果你经常需要将相同的样式又可以创建一个用户定义的风格
// 到Word文档,给addText功能样式的名称:
$phpWord->addFontStyle('myOwnStyle',
array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232'));
$section->addText('Hello world! I am formatted by a user defined style',
'myOwnStyle');
// 你也可以把附加的元素,这样的本地对象:
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Verdana');
$fontStyle->setSize(22);
$myTextElement = $section->addText('Hello World!');
$myTextElement->setFontStyle($fontStyle);
// 最后,写文档:
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('helloWorld.odt');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'RTF');
$objWriter->save('helloWorld.rtf');