PHPword 表格内换行处理

PHPWord文本换行很简单:

$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$section->addText('php点点通-www.phpddt.com');
$section->addTextBreak(1);//换行

但是在添加table的cell单元格中换行,好像没有相应的方法,提供一个PHPWord实现table cell单元格内容换行解决方案如下:
把phpword/writer/word2007/base.php中_writeText()方法替换如下:

protected function _writeText(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Text $text, $withoutP = false) {
        $styleFont = $text->getFontStyle();
        $SfIsObject = ($styleFont instanceof PHPWord_Style_Font) ? true : false;
        //@blog
        $strText = htmlspecialchars($text->getText());
        // 将文本用/n分割成数组
                $str_tmp=explode("/n",$strText);
                // 循环输出数组文本
                for ($i = 0; $i < count($str_tmp); $i++) {
                    if(!$withoutP) {
                        $objWriter->startElement('w:p');
                        $styleParagraph = $text->getParagraphStyle();
                        $SpIsObject = ($styleParagraph instanceof PHPWord_Style_Paragraph) ? true : false;

                        if($SpIsObject) {
                            $this->_writeParagraphStyle($objWriter, $styleParagraph);
                        } elseif(!$SpIsObject && !is_null($styleParagraph)) {
                            $objWriter->startElement('w:pPr');
                            $objWriter->startElement('w:pStyle');
                            $objWriter->writeAttribute('w:val', $styleParagraph);
                            $objWriter->endElement();
                            $objWriter->endElement();
                        }
                    }
                    $strText = htmlspecialchars($text->getText());
                    $strText = PHPWord_Shared_String::ControlCharacterPHP2OOXML($strText);
                    $strText = $str_tmp[$i];
                    $strText = PHPWord_Shared_String::ControlCharacterPHP2OOXML($strText);
                    $objWriter->startElement('w:r');

                    if($SfIsObject) {
                        $this->_writeTextStyle($objWriter, $styleFont);
                    } elseif(!$SfIsObject && !is_null($styleFont)) {
                        $objWriter->startElement('w:rPr');
                        $objWriter->startElement('w:rStyle');
                        $objWriter->writeAttribute('w:val', $styleFont);
                        $objWriter->endElement();
                        $objWriter->endElement();
                    }

                    $objWriter->startElement('w:t');
                    $objWriter->writeAttribute('xml:space', 'preserve'); // needed because of drawing spaces before and after text
                    $objWriter->writeRaw($strText);
                    $objWriter->endElement();
                    $objWriter->endElement(); // w:r
                    if(!$withoutP) {
                        $objWriter->endElement(); // w:p
                    }
                }
    }

只要在表格内容里面 加上 /n就可以换行了!

你可能感兴趣的:(PHP,php)