【问题标题】:how to go new line in cell in table in phpword?如何在phpword表格中的单元格中换行?
【发布时间】:2015-10-24 11:07:24
【问题描述】:

我想从我存在于数据库中的数据创建一个 word 文件.docx。 要完成这项工作,我使用的是 phpword 0.12.0 。 我需要绘制一个表格来将数据放入其中。之后,我需要从数据库中的表中获取每一行以自动进入新行的单元格。 我可以用

完成这项工作
$section->addTextBreak();

但是没有表格,现在我如何在表格内的单元格中完成这项工作? 我正在使用下面的代码,但它不起作用。

$area=array();
$axis=array();
$topic=array();
$table->addRow(900);
$table->addCell(2000, $styleCell)->addText(htmlspecialchars('test1'), $fontStyle);
$table->addCell(2000, $styleCell)->addText(htmlspecialchars('test2'), $fontStyle);
$table->addCell(2000, $styleCell)->addText(htmlspecialchars('test3'), $fontStyle);
$table->addCell(2000, $styleCell)->addText(htmlspecialchars('test4'), $fontStyle);
for ($i = 0; $i < 4; $i++) {
      $table->addRow();
      $table->addCell(2000)->addText(htmlspecialchars($topic{$i}),array('name' => 'Segoe UI Semilight'));
      $table->addCell(3000)->addText(htmlspecialchars($axis{$i}),array('rtl' => true,'name' => 'Segoe UI Semilight'));
      $table->addCell(2000)->addText(htmlspecialchars($area{$i}),array('rtl' => true,'name' => 'Segoe UI Semilight'));
      $table->addCell(2000)->addText(htmlspecialchars($i),array('rtl' => true,'name' => 'Segoe UI Semilight'));
}

【问题讨论】:

  • 那么到底是什么问题?上面的代码似乎工作正常 - 如果您有一些实际数组,其中包含 4 个或更多项目的区域、轴和主题数组 - 它会创建一个表格,其中第一行包含测试单元格,每个 for 循环中都有新行。您在数据库查询或创建表格内容方面有问题吗?

标签: php mysql phpword


【解决方案1】:

正如@Milaza 指出的那样,您可以

// define the cell
$cell = $table->addCell(2000);

// add one line
$cell->addText("Cell 1");

// then add another one
$cell->addText("New line");

我认为这很烦人,因为我必须将一行文本分成多行,而且我有很多单元格文本要中断。所以我在PHPWord/src/PhpWord/Element/Cell.php中创建了(2016-11-08)一个方法:

/**
 * Add multi-line text
 *
 * @return \PhpOffice\PhpWord\Style\Cell
 */
public function addMultiLineText($text, $fStyle = null, $pStyle = null)
{
    // break from line breaks
    $strArr = explode('\n', $text);

    // add text line together
    foreach ($strArr as $v) {
        $this->addText($v, $fStyle, $pStyle);
    }
    return $this;
}

它会从\n 标记中断开文本字符串。

所以当你添加一个单元格时,你可以像这样使用它:

// "$fStyle", "$pStyle" are the old "$fStyle", "$pStyle" you pass to old "addText" method
$table->addCell(2000)->addMultiLineText("Line 1\nLine 2", $fStyle, $pStyle);

输出将如下所示:

Line 1
Line 2

如果你不想修改源代码,我这里已经加进去了。

https://github.com/shrekuu/PHPWord

https://packagist.org/packages/shrekuu/phpword

你可以通过运行来安装这个:

composer require shrekuu/phpword

【讨论】:

    【解决方案2】:

    你必须先创建一个单元格对象,然后使用addText

        $c1=$table->addCell(2000);
        $c1->addText("Cell 1");
        $c1->addText("New line");
    

    【讨论】:

    • 补充一点说明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2016-05-27
    相关资源
    最近更新 更多