在PHPExcel中保留换行符 [英] Perserving newline characters in PHPExcel

查看:370
本文介绍了在PHPExcel中保留换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHPExcel创建Excel文件.源数据是一个关联数组的数组,每个数组都存储一个名称和地址:

I am trying to create an Excel file using PHPExcel. 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
        )
    :
    :
)

如您所见,地址包含换行符.我使用以下代码使用PHP将数据写入Excel文件:

As you can see, the addresses contain newline characters. I am writing this data to an Excel file using PHP using the following code:

$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);

但是,生成的Excel文件不包含我要保留的换行符.

However, the resulting Excel file does not contain the newline characters, which I want to preserve.

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

在PHPExcel网站中的评论中,似乎应该可以这样做,但是我不知道该怎么做.

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.

有人可以帮助我吗?谢谢.

Can anyone help me? THANKS.

推荐答案

您使用"\ n"作为返回字符;并将一个单元格设置为wrap;

You use "\n" as the return character; and a cell needs to be set to wrap;

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

如开发人员文档第4.6.6节所述

as described in section 4.6.6 of the developer documentation

这篇关于在PHPExcel中保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆