56
votes

i have problem with php excel,

i want to make new line in one cell but i can't, i have tried using \n or <br /> but itsn't work. this my code:

$objPHPExcel->getActiveSheet()->setCellValue('H5', 'Hello\nWorld'); // i need this show in two line
$objPHPExcel->getActiveSheet()->getStyle('H5')->getAlignment()->setWrapText(true);

fyi: my format excel is xls not xlsx. many thanks :)

5
Does your actual code reference cell H5 or H% - Mark Baker
@Mark Baker, sorry i just mistype. actually this is for cell H5. i just update my question, many thanks :) - bungdito
OK, second question (seeing as you changed it when you edited): 'Hello\nWorld' or "Hello\nWorld"? Standard PHP quoting for strings applies: the double quotes make a difference to the \n - Mark Baker

5 Answers

119
votes
$objPHPExcel->getActiveSheet()->setCellValue('H5', "Hello\nWorld");
$objPHPExcel->getActiveSheet()->getStyle('H5')->getAlignment()->setWrapText(true);

Works for me...

You should always use double quotes when you add escape sequences in a PHP string.

30
votes

you should use 'r' to break into new line into excel with php

and use double quotes when you add escape sequences in a PHP string.

  $objPHPExcel->getActiveSheet()->setCellValue('H5', "Hello\r World");
  $objPHPExcel->getActiveSheet()->getStyle('H5')->getAlignment()->setWrapText(true);
11
votes

Improved answer based on Ravin and others

$objPHPExcel
  ->getActiveSheet()
  ->setCellValue('H5', "Hello".PHP_EOL." World");

$objPHPExcel
  ->getActiveSheet()
  ->getStyle('H5')
  ->getAlignment()
  ->setWrapText(true);
5
votes

We can set for the default style, so don't need to specify for each cell range:
$objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);

-5
votes

To achieve next line but same cell forxcel export, this is the simplest solution.

<tr>
    <td style="wrap-text: true">
        Test
        <br />
        Test2
    </td>
</tr>