Search code examples
phpmysqlphpexcel

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.

Problem : When I open the excel file, it only contains random gibberish. 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();
}

Solution

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