12

I am using PHPEXxcel to export an HTML Table generated using MYSQL and its like this.

<?php $query = "SELECT `Firstname`,`Lastname`,`Branch`,`Gender`,`Mobileno`, `Email`  
      FROM `student_details` WHERE Branch IN ('$branch') and `Year`='$year' 
         and Tenthresult > '$tenth' and 
      Twelthresult > '$twelth' and (CGPA > '$cgpa' || CGPA = '$cgpa')";  

$result = mysql_query($query);
confirm_query($result);
$objPHPExcel = new PHPExcel(); 
$objPHPExcel->setActiveSheetIndex(0); 

$rowCount = 1; 
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount,'Firstname');
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount,'Lastname');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount,'Branch');
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount,'Gender');
$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount,'Mobileno');
$objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount,'Email');

while($row = mysql_fetch_array($result)){ 
    $rowCount++;
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['0']);
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['1']);
    $objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['2']);
    $objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $row['3']);
    $objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, $row['4']);
    $objPHPExcel->getActiveSheet()->SetCellValue('F'.$rowCount, $row['5']);
} 

$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
$objWriter->save('some_excel_file.xlsx'); 
?>

Its working but it saves the xlsx file in the root folder without showing to user any signs that its being downloaded. This code rund when i click a button.now, can i make it to be downloaded like we download a mail attachment and showing the user in the front end that its being downloaded along with the location.

I tried using

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

With this, i am getting what i wanted above but the xls file downloaded when opened shows the message 'The File you are trying to open 'filename' is in a different format than the specified extension.....etc.Do you want to open now?

On opening it contains either the entire HTML Page or its simply blank... Can anybody help me..?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ankur
  • 269
  • 2
  • 4
  • 15
  • have a look, http://www.sitepoint.com/forums/showthread.php?622074-PHP-export-to-xlsx – Rafee Apr 09 '13 at 07:00
  • Note that you are __not__ creating an HTML Page.... HTML is a markup used for web pages. With PHPExcel, you are creating an Excel file using either the BIFF-8 file format or the OfficeOpenXML format. – Mark Baker Apr 09 '13 at 08:13

4 Answers4

18

Spreadsheets 101

There are many different spreadsheet file formats, each with their own different filename extensions, and that can be sent to a web browser using different mime types. These are described in the PHPExcel documentation, and each has its own different Writer in PHPExcel. You're mismatching two different formats

BIFF Format

  • Used by Microsoft Excel between versions 95 and 2003 File

  • extension: xls

  • PHPEXcel Writer: PHPExcel_Writer_Excel5

  • Mime Type: application/vnd.ms-excel

OfficeOpenXML Format

  • Used by Microsoft Excel since version 2007

  • File extension: xlsx

  • PHPEXcel Writer: PHPExcel_Writer_Excel2007

  • Mime Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Don't mix and match: if you do, then Excel will (and justifiably) complain. If you want a BIFF file, use PHPExcel's BIFF Writer (Excel5), a file extension of .xls, and the mime type listed above for BIFF Format. If you want an OfficeOpenXML file, then use PHPExcel's Excel2007 Writer, a file extension of .xlsx, and the mime type listed above for OfficeOpenXML.

EDIT

Note that the examples provided with the PHPExcel distribution include 01simple-download-xls.php and 01simple-download-xlsx.php to demonstrate exactly what you want

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Can I ask whoever downvoted to actually provide an explanation for it? As far as I'm aware, everything I've stated in my answer is factually correct, and directly answers the OP's question, including reference to the examples provided in the PHPExcel package (showing the use of php://output as the filename to use for sending data to the browser). – Mark Baker Apr 09 '13 at 08:48
  • You are right But using xlsx when i open the file i am getting the warning that i mentioned above and when given yes it shows some unusual data...what to do for that? – Ankur Apr 09 '13 at 13:06
  • Please be more detailed: explain `unusual data` – Mark Baker Apr 09 '13 at 13:10
  • It means which can't be understood e.g. YýPKÝ‘‰BÍKR"x#xl/worksheets/_rels/sheet1.xml.relsMŒ1!{_A¶÷@cÌq×ù£Øp+a!,1ú{)-'“™yýä¤ÞÔ$¶p˜(bW¶ÈÞÂã~ÝŸAIGÞ0&_X—Ý|£„}4b5&,Bïõ¢µ¸@e*•x˜giûÀæuE÷BOúhÌI·ÿèåPKÝ‘‰BG’D²Xð[Content_Types].xmlPKÝ‘‰B¶78éK‰_rels/.relsPKÝ‘‰B„$±Vé¹›xl/_rels/workbook.xml.relsPKÝ‘‰B×Íê†;¼docProps/app.xmlPKÝ‘‰B„³ŸrpdocProps/core.xmlPKÝ‘‰Bs‘{Y³¦xl/theme/theme1.xmlPKÝ‘‰Bòu0ö*õxl/sharedStrings.xmlPKÝ‘‰Bâ_œÞùh Thankyou – Ankur Apr 10 '13 at 13:08
  • 1
    That `unusual data` is part of the binary stream that comprises an xlsx file.... if MS Excel can't open that, then it means somewhere there's some corruption in the file - open in a text editor and look for leading/trailing whitespace characters, or any obvious plaintext error message text within the binary data – Mark Baker Apr 10 '13 at 13:12
  • Thats ok but what should i do now.i mean,can;t i use headers at all? – Ankur Apr 12 '13 at 07:15
  • You should be using headers if you need to send the file to a browser for the `open/save` dialogue - but the filestream generated by PHPExcel must be the __only__ content sent to the browser... if there is anthing else sent as outout then it will be incorporated into the filestream and corrupt it so that the file can't be opened. That anything might include whitespace from your script, or other echoed content, or PHP error messages – Mark Baker Apr 12 '13 at 07:50
  • Would somebody care to explain the downvotes? I'm interested in knowing where and why I'm wrong – Mark Baker Mar 03 '14 at 16:42
  • Your answer looks informative, but does not solve the problem, please add some instructions on how to use each writer – Peyman Mohamadpour Jul 24 '16 at 23:41
  • Providing instruction is what the documentation and the examples in the repository are for.... and there's hundreds of examples there, demonstrating every file format that PHPExcel supports – Mark Baker Jul 07 '17 at 08:10
9

Just adding those headers only sends those headers. The rest of your code is still the same, so you're saving your xls to your root folder like you used to.

Sending the headers only makes the page you would normally see be send with xls headers. Something which is not what you want, and you're getting your HTML page but with the wrong headers.

What you need to do is send those headers and then stream the xlsx.

Looking at a random thread (I know, bad idea, but this'll get you a headstart on what to do) here, you can find examples like this:

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=$filename.xls");
header("Content-Transfer-Encoding: binary ");
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
$objWriter->setOffice2003Compatibility(true);
$objWriter->save('php://output');
Nanne
  • 64,065
  • 16
  • 119
  • 163
2

I do it with using below snippet.

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test_file.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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
Zaid Bin Khalid
  • 748
  • 8
  • 25
0

try this ..

header('Content-Type: application/vnd.ms-excel');
    $filename = "Reports".date("d-m-Y-His").".xls";
    header('Content-Disposition: attachment;filename='.$filename .' ');
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');