PHPEXCEL - 数组到CSV文件 - 第一行中的所有标题

时间:2017-10-20 08:00:09

标签: php phpexcel

我正在尝试使用PHPEXCEL创建CSV文件。这是我的代码:

<?php

/** Include PHPExcel */
require_once($path.'PHPExcel/Classes/PHPExcel.php');
require_once($path.'PHPExcel/Classes/PHPExcel/IOFactory.php');

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

$res_headers = array(
    'A' => 'Title',
    'B' => 'Custom Label',
    'C' => 'CustomLabel',
    'D' => 'Description',
    'E' => 'PicURL',
    'F' => 'C:Herstellernummer',
    'G' => 'StartPrice'
);

$ff = array_flip($res_headers);
$dd = array_values($ff);

$objPHPExcel->setActiveSheetIndex(0);
foreach($res_headers AS $key => $value)
{
    $objPHPExcel->getActiveSheet()->setCellValue($key.'1', $value);
}

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="simple.csv"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->setDelimiter(','); 
$objWriter->setEnclosure('');
$objWriter->setLineEnding("\r\n");
$objWriter->save('php://output');

?>

问题在于行。在生成的CSV文件中,所有行如:标题,自定义标签,CustomLabel等都在第一行(A1)中。我想补充一下:

  • &#34;名称&#34;在A1行,
  • &#34;&#34; B1&#34;中的自定义标签;行,
  • &#34; CustomLabel&#34; in&#34; C1&#34;行,
  • ... 等

但现在,一切都在第一行(A1):&#34;标题,自定义标签,CustomLabel,描述,PicURL,C:Herstellernummer,StartPrice&#34;。为什么?你可以帮帮我吗?

感谢。

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。只需改变一下:

$objWriter->setDelimiter(','); 
$objWriter->setEnclosure('');
$objWriter->setLineEnding("\r\n");

为此:

$objWriter->setDelimiter(';'); 
$objWriter->setEnclosure('"');
$objWriter->setLineEnding("\r\n");

就是这样。