简体   繁体   English

在PHPExcel中保留换行符

[英]Perserving newline characters in PHPExcel

I am trying to create an Excel file using PHPExcel. 我正在尝试使用PHPExcel创建一个Excel文件。 The source data is an array of associative arrays, each of which stores a name and address: 源数据是关联数组的数组,每个关联数组都存储一个名称和地址:

Array
(
    [0] => Array
        (
            [name] => Joe Bloggs
            [address] => 10 Main St 
Bayside 
Big Town ABC123
    )

    [1] => Array
        (
            [name] => Mary Bloggs
            [address] => 18 Bridge St
Riverside
Small Town XYZ987
        )
    :
    :
)

As you can see, the addresses contain newline characters. 如您所见,地址包含换行符。 I am writing this data to an Excel file using PHP using the following code: 我使用以下代码使用PHP将数据写入Excel文件:

$phpExcel = new PHPExcel();

$phpExcel->setActiveSheetIndex(0);
$phpExcel->getActiveSheet()->getCell('A1')->setValue("Name");
$phpExcel->getActiveSheet()->getCell('B1')->setValue("Address");
$index = 2;
foreach($rows as $row) {
    $phpExcel->getActiveSheet()->getCell('A'.$index)->setValue($row["name"]);
    $phpExcel->getActiveSheet()->getCell('B'.$index)->setValue($row["address"]);
    $index++;
}
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
$filename = "outputs/excel/data.xlsx";
$objWriter->save($filename);

However, the resulting Excel file does not contain the newline characters, which I want to preserve. 但是,生成的Excel文件不包含我要保留的换行符。

Name         Address
Joe Bloggs   10 Main St Bayside Big Town ABC123
Mary Bloggs  18 Bridge St Riverside Small Town XYZ987
...

From comments in the PHPExcel website, it seems that it should be possible to do this, but I cannot figure out how to do this. 从PHPExcel网站上的评论看来,应该可以这样做,但是我不知道该怎么做。

Can anyone help me? 谁能帮我? THANKS. 谢谢。

Try using this instead of "\\n": 尝试使用它代替“ \\ n”:

$lfcr = chr(10) . chr(13);

then replace "\\n" everywhere with $lfcr, like this: 然后在各处用$ lfcr替换“ \\ n”,如下所示:

setValue("First line". $lfcr . "second Line" . $lfcr . "Third Line");

You use "\\n" as the return character; 您使用“ \\ n”作为返回字符; and a cell needs to be set to wrap ; 并且需要设置一个wrap ;

$objPHPExcel->getActiveSheet()
    ->getCell('A1')
    ->setValue("First line\nSecond Line\nThird Line");
$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getAlignment()
    ->setWrapText(true);

as described in section 4.6.6 of the developer documentation 如开发人员文档第4.6.6节所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM