Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel will not export to CSV

I am banging my head against a wall trying to figure out why I cannot get PHPExcel to output a csv file. Oddly enough, this works in Internet Explorer- it outputs as csv, but in every other browser I try it outputs it as an xls that Excel refuses to open.

Any pointers would be exceedingly appreciated.

error_reporting(E_ALL);
$username="blah";
$password="blahz";
$database="hollatme";
$sqlsrv="localhizzost";
date_default_timezone_set('US/Central');
$currenttime=date("m-d-Y");

require_once 'Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties();


$viewinv = mysql_connect($sqlsrv,$username,$password);
if (!$viewinv) { die('Could not connect to SQL server. Contact administrator.'); }
mysql_select_db($database, $viewinv) or die('Could not connect to database. Contact administrator.');
$query = "select somestuff from someplace;";
$result = mysql_query($query);

if ($result = mysql_query($query) or die(mysql_error())) {
   $objPHPExcel = new PHPExcel();
   $objPHPExcel->getActiveSheet()->setTitle('CYImport'.$currenttime.'');

$rowNumber = 1;
$headings = array('abunchof','differentheadings');
$objPHPExcel->getActiveSheet()->fromArray(array($headings),NULL,'A'.$rowNumber);
$rowNumber++;
while ($row = mysql_fetch_row($result)) {
   $col = 'A';
   foreach($row as $cell) {
      $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
      $col++;
   }
   $rowNumber++;
}


   $objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->setDelimiter(',');
$objWriter->setEnclosure('');
$objWriter->setLineEnding("\r\n");
$objWriter->setSheetIndex(0);
$objWriter->save('blah '.$currenttime.'.csv');


   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
   header('Content-Disposition: attachment;filename="CY Import '.$currenttime.'"..csv"');
   header('Cache-Control: max-age=0');

   $objWriter->save('php://output');
   exit();
}
echo 'Contact your Administrator. No data received from server.';
like image 469
floppyraid Avatar asked Jun 14 '11 15:06

floppyraid


1 Answers

You could try to change the MIME type to

header('Content-type: text/csv');
like image 199
Ryan Avatar answered Oct 23 '22 06:10

Ryan