简体   繁体   中英

PHPEXCEL - array to CSV file - all headers in first row

I'm trying to create a CSV file using PHPEXCEL. This is my code:

<?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');

?>

The problem is in rows. In generated CSV file, all rows like: Title, Custom Label, CustomLabel etc. are in first row (A1). I want to add:

  • "Title" in A1 row,
  • "Custom Label in "B1" row,
  • "CustomLabel" in "C1" row,
  • ... etc.

But now, everything is in first row (A1): "Title,Custom Label,CustomLabel,Description,PicURL,C:Herstellernummer,StartPrice". Why? Can u help me?

Thanks.

OK, I found solution. Just change this:

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

for this:

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

And that's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM