繁体   English   中英

PHPExcel下载无法正常工作

[英]PHPExcel download not working properly

我正在尝试创建一个页面,该页面允许用户将SQL表的内容下载到Excel文件中。

问题:当我打开excel文件时,它仅包含随机的乱码。 一个例子 -

PKQ=DG’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¦

这是我的代码-

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

$download="";
if (isset($_GET['surveyid'])) {
//Survey ID
$download = $_GET['surveyid'];
require_once('../Classes/PHPExcel.php');

$query="SELECT b.question_id as qid,
                a.question as ques,
                b.response as response,
                count(b.response) as cnt
          FROM v3_sai.survey_responses b 
          INNER JOIN v3_sai.survey_questions a 
             ON a.id = b.question_id 
                AND a.survey_id=".intval($download)."
          group by b.response, a.question
          order by b.question_id";
          var_dump($query);
$resultdl= mysql_query($query) or die(mysql_error());
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowcount=1;
while($row = mysql_fetch_array($resultdl)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowcount, $row['qid']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowcount, $row['ques']); 
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowcount, $row['response']);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowcount, $row['cnt']); 
$rowCount++; 
} 
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
$objWriter->save('php://output');
die();
}

如果您下载xls文件(BIFF),请使用PHPExcel_Writer_Excel5 Writer; 如果您要下载.xlsx文件(OfficeOpenXML),请使用PHPExcel_Writer_Excel2007 Writer: 不要混搭...这就是您的问题。 您正在使用Excel2007 Writer创建.xlsx(OfficeOpenXML)文件,但设置标头以告知浏览器期望使用.xls(BIFF)文件

推荐的.xls(BIFF)下载头是:

// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
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

推荐的.xlsx(OfficeOpenXML)下载头是:

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
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

请注意, Content-TypeContent-Disposition可能被浏览器区分大小写,因此Content-TypeContent-type ....并不相同,我相信这也可能给您带来问题

我知道我对此可能会有所回应,但是以上都不对我有用。 使用ob_clean();是正确的ob_clean(); 将删除所有缓存的资料,以免干扰返回的标题和文件内容。 重要的是您要在哪里清理多余的垃圾。 因此,经过几天的ob_clean(); ,我注意到您需要ob_clean(); 在标题之前。 如果您在其他地方执行此操作,则会遇到同样的问题。 这是对我有用的示例代码。

            ob_clean();
            $fileName = "Test.xlsx";
            # Output headers.
            header("Set-Cookie: fileDownload=true; path=/");
            header("Cache-Control: private");
            header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            header("Content-Disposition: attachment; filename='".$fileName."'");
            // 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
            # Output file.
            $return->save('php://output');
            die();

你可以这样使用

<?php 
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=abc".xls");
header("Pragma: no-cache");
header ("Expires: 0");
?>
    <table width="100%" border="1">
        <tr>
            <td>
                <h1> qid</h1>
            </td>
            <td>
                <h1> ques</h1>
            </td>
            <td>
                <h1> response</h1>
            </td>
            <td>
                <h1> cnt</h1>
            </td>
        </tr>

    while($row = mysql_fetch_array($resultdl)){
        <tr>
            <td>
                <?php echo $row['qid']; ?>
            </td>
            <td>
                <?php echo $row['ques']; ?>
            </td>
            <td>
                <?php echo $row['response']; ?>
            </td>
            <td>
                <?php echo $row['cnt']; ?>
            </td>
        </tr>

    <?php } ?>

    </table>

尝试此操作并禁用错误报告。

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=file.xls");
header("Content-Transfer-Encoding: binary ");
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
$objWriter->setOffice2003Compatibility(true);
$objWriter->save('php://output');

我遇到了同样的问题,终于找到了造成这个问题的原因。 $objWriter->save('php://output')被调用之前的某个地方,输出缓冲区被无意写入。 您可以在$objWriter->save('php://output')之前通过var_dump(ob_get_contents())进行测试。

速战速决是添加ob_开始()在脚本的开头,然后ob_​end_​clean()之前只是$objWriter->save('php://output')但完美的解决将是查找输出缓冲区的填充位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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