How to go to a new row in a cell in a table in phpword?
I want to create a text file .docx
from my data existing in the database. I am using phpword 0.12.0 to do this job. I need to draw a table to place data inside it. After that, I need to get each row from the table in the database to automatically jump to the new row cell. I can make this work with
$section->addTextBreak();
but without the table, now how can I accomplish this task in a cell within a table? I am using below code but it doesn't work.
$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'));
}
source to share
As @Milaza pointed out, you can
// define the cell
$cell = $table->addCell(2000);
// add one line
$cell->addText("Cell 1");
// then add another one
$cell->addText("New line");
I think this is annoying since I have to split a line of text into multiple lines and I have a lot of cell text to break. So I created (2016-11-08) a method in PHPWord/src/PhpWord/Element/Cell.php
:
/**
* 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;
}
It breaks the text string with \n
.
So when you add a cell, you can use it like:
// "$fStyle", "$pStyle" are the old "$fStyle", "$pStyle" you pass to old "addText" method
$table->addCell(2000)->addMultiLineText("Line 1\nLine 2", $fStyle, $pStyle);
The result will look like this:
Line 1
Line 2
If you don't want to change the source code, I've already added it here.
https://github.com/shrekuu/PHPWord
https://packagist.org/packages/shrekuu/phpword
You can simply install it by running:
composer require shrekuu/phpword
source to share