Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simulate alt+enter to create newline within cell CSV output from PHP to Excel

Tags:

php

csv

excel

I'm generating a CSV file using PHP and opening it in Excel. Adding "\n" at the end of each record creates a new line and works perfectly, however I need to figure out a way to create a newline within a cell itself. The same functionality that alt+enter achieves when entering data manually into Excel. Does anyone have any insight as to how this can be performed? I have tried "\n\r", "\n", chr(10), none of which seem to work, just keep getting a complete new line instead of newline within the same cell.

What I want to achieve is a header that looks like this... This is all in one row in Excel..

CELL

Start Date End Date

Thank you for any help provided!

like image 677
Phil Avatar asked Jun 21 '13 15:06

Phil


People also ask

How do I handle line breaks in a CSV file using PHP?

use implode(PHP_EOL) will do the trick.

How do I add a line break in CSV?

To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a . csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.

What is the code for alt enter in excel?

The documentation of excel say that alt+enter puts char(10). char(10) is Line-Feed (LF), so it is the same character as \n in java.

What is a line feed in CSV file?

A CSV file contains a set of records separated by a carriage return/line feed (CR/LF) pair (\r\n), or by a line feed (LF) character. Each record contains a set of fields separated by a comma. If the field contains either a comma or a CR/LF, the comma must be escaped with double quotation marks as the delimiter.


2 Answers

How are you creating the csv file?
If you're doing it correctly and using fputcsv, having a line break within a cell wouldn't cause an issue.

Documentation to fputcsv

like image 100
Trenton Trama Avatar answered Oct 13 '22 11:10

Trenton Trama


I have tried "\n\r", "\n",

Use "\r\n" :) Check the wiki article about 'Newline'

But note that you'll have to use double quotes. " otherwise PHP will not handle meta characters.

like image 32
hek2mgl Avatar answered Oct 13 '22 10:10

hek2mgl