简体   繁体   English

PHPExcel下载无法正常工作

[英]PHPExcel download not working properly

I am trying to create a page that allows a user to download the contents of an SQL table, into an excel file. 我正在尝试创建一个页面,该页面允许用户将SQL表的内容下载到Excel文件中。

Problem : When I open the excel file, it only contains random gibberish. 问题:当我打开excel文件时,它仅包含随机的乱码。 An example - 一个例子 -

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¦

This is my code - 这是我的代码-

<?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();
}

If youre downloading an xls file (BIFF), use the PHPExcel_Writer_Excel5 Writer; 如果您下载xls文件(BIFF),请使用PHPExcel_Writer_Excel5 Writer; if you're downloading an .xlsx file (OfficeOpenXML), use the PHPExcel_Writer_Excel2007 Writer: DON'T mix and match... that's your problem. 如果您要下载.xlsx文件(OfficeOpenXML),请使用PHPExcel_Writer_Excel2007 Writer: 不要混搭...这就是您的问题。 You're creating an .xlsx (OfficeOpenXML) file using the Excel2007 Writer, but setting the headers to tell the browser to expect an .xls (BIFF) file 您正在使用Excel2007 Writer创建.xlsx(OfficeOpenXML)文件,但设置标头以告知浏览器期望使用.xls(BIFF)文件

Recommended headers for an .xls (BIFF) download are: 推荐的.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

Recommended headers for an .xlsx (OfficeOpenXML) download are: 推荐的.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

Note that Content-Type , Content-Disposition , may be treated as case-sensitive by browsers, so Content-Type is not the same as Content-type .... and I believe that may also give you problems 请注意, Content-TypeContent-Disposition可能被浏览器区分大小写,因此Content-TypeContent-type ....并不相同,我相信这也可能给您带来问题

I know i might be responding a bit late to this but none of the above worked for me. 我知道我对此可能会有所回应,但是以上都不对我有用。 It's true using ob_clean(); 使用ob_clean();是正确的ob_clean(); will remove any cached material so that it does not interfere with the returned headers + file content. 将删除所有缓存的资料,以免干扰返回的标题和文件内容。 What matters is where do you clean of the extra gibberish. 重要的是您要在哪里清理多余的垃圾。 So after days of scratching my head i've noticed that you need to ob_clean(); 因此,经过几天的ob_clean(); ,我注意到您需要ob_clean(); right before the headers. 在标题之前。 If you do it somewhere else you will have the same problem. 如果您在其他地方执行此操作,则会遇到同样的问题。 Here is a sample code that worked for me. 这是对我有用的示例代码。

            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();

You can use like this 你可以这样使用

<?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>

Try this and disable error reporting. 尝试此操作并禁用错误报告。

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

I met with the same problem and finally found what was causing it. 我遇到了同样的问题,终于找到了造成这个问题的原因。 Somewhere before $objWriter->save('php://output') is called the output buffer is being written to unintentionally. $objWriter->save('php://output')被调用之前的某个地方,输出缓冲区被无意写入。 You can test this by var_dump(ob_get_contents()) just before $objWriter->save('php://output') . 您可以在$objWriter->save('php://output')之前通过var_dump(ob_get_contents())进行测试。

A quick fix would be to add ob_​start() at the beginning of the script and then ob_​end_​clean() just before $objWriter->save('php://output') but the perfect fix would be to find where the output buffer is being filled in. 速战速决是添加ob_开始()在脚本的开头,然后ob_​end_​clean()之前只是$objWriter->save('php://output')但完美的解决将是查找输出缓冲区的填充位置。

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

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