PhpExcel 单元格中的新行

PhpExcel new line in cell

我的工作:

  1. 从数据库查询数据
  2. 分解数据并插入\n
  3. 准备数组
  4. 打开模板
  5. 将数组插入模板
  6. 尝试用新行替换 \n

如何找到 \n 并插入新行?例如,我在 A1 中有下一个文本 "One\nTwo"。我从 A1

读取文本
$ltr='A1';
$vle=$spreadsheet->getActiveSheet()->getCell($ltr);

在此之后,我尝试在 A1 中再次插入 A1 中的文本,并在一个单元格中用新行替换 \n

$spreadsheet->getActiveSheet()->getCell($ltr)->setValue("${vle}");
$spreadsheet->getActiveSheet()->getStyle($ltr)->getAlignment()->setWrapText(true);

但这对我不起作用。

例如:

因此,如果我打开带有文本的模板,我无法替换单元格中的 \n。我能做什么?

Upd. 我尝试使用 char(10) 并插入公式(例如)="hello"&char(10)&"world" 但仅插入 ="hello"&char(10)

在 excel 公式中使用 "char(10)"。 & = concantinate,和 char(10) = \n

$textWithNewLine = '="hello"&char(10)&"world"';
$spreadsheet->getActiveSheet()->getCell($ltr)->setValue($textWithNewLine);

当我 explode/implode str 并插入 \n 时,我使用 ''。需要使用“”

implode("\n", $array);

如果您问的是 this issue on the PHPspreadsheet github issues log,那么这是您对 PHP 字符串的理解有问题。

$dataArray = [
    ['2010', 'Q1', 'United\nStates', 790],
    ['2010', 'Q2', 'United States', 730],
    ['2010', 'Q3', 'United States', 860]
]

单引号中的 '\n' 被视为文字 \n;双引号中的 "\n" 被视为换行符。因此,要么使用双引号构建数组:

$dataArray = [
    ['2010', 'Q1', "United\nStates", 790],
    ['2010', 'Q2', "United States", 730],
    ['2010', 'Q3', "United States", 860]
]

或使用 str_replace:

将文字 \n 转换为新行
$modified = str_replace('\n', "\n", $original);

如果您在 Moodle Excel 应用程序中使用 MoodleExcelWorkbook class,并且您想在单元格中设置自动行 wrap/break,请使用如下代码:

require_once $CFG->libdir . '/excellib.class.php';
$workbook = new \MoodleExcelWorkbook("-");
$workbook->send('YOUR_FILE_NAME.xlsx');
$worksheet = $workbook->add_worksheet('YOUR_SHEET_NAME');
/* do your some stuff here */
/* make 'text_wrap' => true in $format attribute */
$worksheet->write_string(1/*row*/, 1/*col*/, 'YOUR_VALUE', ['text_wrap' => true]);
$workbook->close();