Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing a new line in a csv file cell

I am generating an CSV file in php. I need to print the text in new line inside a cell(I can do this in excel using Ctrl+Enter or Alt+Enter). For that I tried using '\n', '\r', but nothing helped. How can I achieve this?

I am using yii extension ECSVExport to generate csv.

I want an output like this:

ID  Value
1   A
    B
2   C
3   E
    FF
    G
4   X
like image 492
Quicksilver Avatar asked Jul 03 '13 12:07

Quicksilver


People also ask

How do I create a new line in a CSV file?

New Line CharactersWindows standard CR+LF or Unix-like systems (Linux, Mac) standard LF may be used as new line character.

What is line separator in CSV?

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

How do you write data on multiple lines but in the same cell of a CSV file?

If you are talking about storing a line break inside a field in a csv file, you can try using a text delimiter like double quotes.


2 Answers

Try this

"\n"

inside double quote

like image 180
Samy Massoud Avatar answered Sep 17 '22 12:09

Samy Massoud


Use "\n" inside the cell value (wrapped in ") and "\r\n" for your end-of-record marker. If your cell entry include multiple lines, then you must enclose it in "

$fh = fopen('test1.csv', 'w+');
fwrite($fh, "sep=\t" . "\r\n");
fwrite($fh, 'A' ."\t" . 'B' . "\t" . 'C' . "\r\n");
fwrite($fh, 'D' ."\t" . "\"E\nF\nG\"" . "\t" . 'H' . "\r\n");
fclose($fh);

or (working with variables)

$varA = 'A';
$varB = 'B';
$varC = 'C';
$varD = 'D';
$varE = 'E';
$varF = 'F';
$varG = 'G';
$varH = 'H';
$fh = fopen('test2.csv', 'w+');
fwrite($fh, "sep=\t"."\r\n");
fwrite($fh, $varA . "\t" . $varB . "\t" . $varC . "\r\n");
fwrite($fh, $varD . "\t" . "\"$varE\n$varF\n$varG\"" . "\t" . $varH . "\r\n");
fclose($fh);

or (using fputcsv())

$fh = fopen('test3.csv', 'w+');
fwrite($fh, "sep=\t" . "\r\n");
fputcsv($fh, array('A', 'B', 'C'), "\t");
fputcsv($fh, array('D', "E\nF\nG", 'H'), "\t");
fclose($fh);

or (using fputcsv() and working with variables)

$varA = 'A';
$varB = 'B';
$varC = 'C';
$varD = 'D';
$varE = 'E';
$varF = 'F';
$varG = 'G';
$varH = 'H';
$fh = fopen('test4.csv', 'w+');
fwrite($fh, "sep=\t" . "\r\n");
fputcsv($fh, array($varA, $varB, $varC), "\t");
fputcsv($fh, array($varD, "$varE\n$varF\n$varG", $varH), "\t");
fclose($fh);
like image 29
Mark Baker Avatar answered Sep 20 '22 12:09

Mark Baker