php 在 csv 文件单元格中打印新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17447442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printing a new line in a csv file cell
提问by Khaleel
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+Enteror Alt+Enter). For that I tried using '\n'
, '\r'
, but nothing helped. How can I achieve this?
我正在用 php 生成一个 CSV 文件。我需要在单元格内的新行中打印文本(我可以使用Ctrl+Enter或Alt+在 excel 中执行此操作Enter)。为此,我尝试使用'\n'
, '\r'
,但没有任何帮助。我怎样才能做到这一点?
I am using yii extension ECSVExportto generate csv.
我正在使用yii扩展ECSVExport来生成 csv。
I want an output like this:
我想要这样的输出:
ID Value
1 A
B
2 C
3 E
FF
G
4 X
回答by Samy Massoud
Try this
尝试这个
"\n"
inside double quote
双引号内
回答by Mark Baker
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 mustenclose it in "
"\n"
在单元格值内使用(包裹在 中"
)和"\r\n"
记录结束标记。如果您的单元格条目包含多行,则必须将其括在"
$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()
)
或(使用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)
或(使用fputcsv()
和处理变量)
$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);