PHPExcel生成完全输出

时间:2011-05-31 18:15:31

标签: php mysql phpexcel

问候,

我无法弄清楚如何正确使用PHP,特别是PHPExcel。我已经阅读了关于这个主题的多篇帖子,但我一直在圈子里跑来跑去。以下是我提出的代码的相关部分:

$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 unit_id,config,location from inventory;";
$result = mysql_query($query);

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

$rowNumber = 1;
$headings = array('Unit ID','Config','Location');
$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 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

   header('Content-Type: application/vnd.ms-excel');
   header('Content-Disposition: attachment;filename="myFile.xls"');
   header('Cache-Control: max-age=0');

   $objWriter->save('php://output');
   exit();
}
echo 'a problem has occurred... no data retrieved from the database';

PHPExcel肯定会从查询中输出数据,我可以看到明文的点点滴滴,但它被大量的随机字符所包围,好像我正在查看压缩或编译的数据片段的内容。 / p>

例如:

PKâh¿>G’D²Xð[Content_Types].xml­”MNÃ0…÷œ"ò%nY „švAa •(0ö¤±êØ–gúw{&i‰@ÕnbEö{ßøyìÑdÛ¸l mð¥‘×ÁX¿(ÅÛü)¿’òF¹à¡;@1_滘±Øc)j¢x/%ê…Eˆày¦ 

任何指针都会非常感激

2 个答案:

答案 0 :(得分:14)

您的问题当然是输出的内容多于Excel数据(包含在输出缓冲区中)。

要解决您的问题,请致电

  ob_clean(); //this will clean the output buffer

发送标题之前。

答案 1 :(得分:4)

通过将正确的编写器类型与正确的内容类型和文件扩展名相匹配,可能会解决问题。

XLSX(office 2007 +):

Writer      : Excel2007 (PHPExcel_Writer_Excel2007)
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

XLS(2007年之前):

Writer      : Excel5 (PHPExcel_Writer_Excel5)
Content-Type: application/vnd.ms-excel