PHPWord 库来生成和处理 Word 文档非常丝滑!

1、安装

在tp项目目录下运行以下命令行

composer require phpoffice/phpword

2、在TP6中引用PhpWord类

use PhpOfficePhpWordPhpWord;
use PhpOfficePhpWordElementSection;
use PhpOfficePhpWordExceptionException;

3、示例

$phpWord = new PhpWord();
        $section = $phpWord->addSection();
        $section->addText(
        '"Learn from yesterday, live for today, hope for tomorrow. '
        . 'The important thing is not to stop questioning." '
        . '(Albert Einstein)'
        );
        $section->addText(
    '"Great achievement is usually born of great sacrifice, '
        . 'and is never the result of selfishness." '
        . '(Napoleon Hill)',
    array('name' => 'Tahoma', 'size' => 10)
);
        $fontStyleName = 'oneUserDefinedStyle';
        $phpWord->addFontStyle(
                            $fontStyleName,
                            array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
        $section->addText(
                        '"The greatest accomplishment is not in never falling, '
                        . 'but in rising again after you fall." '
                        . '(Vince Lombardi)',
                        $fontStyleName
);

        // Adding Text element with font customized using explicitly created font style object...
        $fontStyle = new PhpOfficePhpWordStyleFont();
        $fontStyle->setBold(true);
        $fontStyle->setName('Tahoma');
        $fontStyle->setSize(13);
        $myTextElement = $section->addText('"Believe you can and you're halfway there." (Theodor Roosevelt)');
        $myTextElement->setFontStyle($fontStyle);
        
        // Saving the document as OOXML file...
        $objWriter = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save('helloWorld.docx');

4、查看生成的word内容

在public文件夹下能找到刚才生成的helloWorld.docx

5、常用的几个方法

        addTitle()//添加标题到文档。
    
        addText()//添加文本到文档。
    
        addTable()//添加表格到文档。
    
        addImage()//添加图像到文档。
    
        addPageBreak()//添加分页符到文档。
    
        addSection()//添加文档的节(section)。
    
        addLink()//添加超链接到文档。 样式和格式设置方法:
    
        setDefaultFontName()//设置默认字体名称。
    
        setDefaultFontSize()// 设置默认字体大小。
    
        setDefaultParagraphStyle()//设置默认段落样式。
    
        addFontStyle()//添加字体样式。
    
        addListItemStyle()//添加列表项样式。
    
        addTableStyle()// 添加表格

6、中文手册

https://phpword-zh.readthedocs.io/zh-cn/latest/index.html