PHPExcel不会导出为CSV

时间:2011-06-14 15:46:25

标签: php mysql phpexcel

我正在撞墙,试图找出为什么我无法让PHPExcel输出csv文件。奇怪的是,这可以在Internet Explorer中运行 - 它输出为csv,但在其他所有浏览器中我尝试将其输出为Excel拒绝打开的xls。

任何指针都会非常感激。

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.';

1 个答案:

答案 0 :(得分:10)

您可以尝试将MIME类型更改为

header('Content-type: text/csv');