File format or extension invalid PHPExcel - php

I try to use PHPExcel library for my report, this is my first time i use PHPExcel ,but error dialog appear telling that file format / extension invalid ,this is the syntax :
include '../_class/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Rizal")
->setTitle("Laporan Anggota")
->setSubject("anggota")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Create the worksheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A7', "No")
->setCellValue('B7', "NIS")
->setCellValue('C7', "NISN")
->setCellValue('D7', "Name")
->setCellValue('E7', "J.K")
->setCellValue('F7', "Birth")
->setCellValue('G7', "Address")
->setCellValue('H7', "Job")
// Redirect output to a client’s web browser (Excel2007)
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Test.xlsx"');
header('Cache-Control: max-age=0');
anyone can help me to solve it?

Try this example
<?php
$name = rand('0','10000').'.xlsx';
$n = rand('0','100');
error_reporting(E_ALL);
include 'PHPExcel/Classes/PHPExcel.php';
include 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
$o = new PHPExcel();
$o->getProperties()->setCreator('Creator');
$o->getProperties()->setLastModifiedBy('Last Modified');
$o->getProperties()->setTitle("Office 2007 XLSX Document ");
$o->getProperties()->setSubject('Subject');
$o->getProperties()->setDescription("Office 2007 XLSX, generated using PHP classes.");
$o->setActiveSheetIndex(0);
$o->getActiveSheet()->SetCellValue('A1', 'Name');
$o->getActiveSheet()->SetCellValue('B1', 'Rating');
$o->getActiveSheet()->SetCellValue('A2', 'Shawshank Redemption');
$o->getActiveSheet()->SetCellValue('B2', $n);
$o->getActiveSheet()->SetCellValue('A3', 'A Clockwork Orange');
$o->getActiveSheet()->SetCellValue('B3', $n);
$o->getActiveSheet()->setTitle('Films');
$objWriter = new PHPExcel_Writer_Excel2007($o);
$objWriter->save('excel/'.$name); // exce/ = filepath
?>
I think the problem you are having relates to the $objWriter variable.

Related

PHPExcel create a new file

I am trying to create a new Excel file by using PHPExcel library with this code :
include ('/lib/PHPExcel/PHPExcel/IOFactory.php');
include ('/lib/PHPExcel/PHPExcel.php');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("admin")
->setLastModifiedBy("admin")
->setTitle("Test")
->setSubject("template file")
->setDescription("template file")
->setKeywords("Prout");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(dirname(__FILE__).'/file/test.xlsx');
The file is created, but when i try to open it my excel 2010 tells me there is unreadable content inside the file and i can't open it.
I tried a different way on a different forum but i am always arriving to the same result. I do this manipulation by using Ajax with jquery. Can this be the cause of this error?
I find how to resolve my problem ... but only half of it. Because it's work with this code :
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("Temporaris")
->setLastModifiedBy("Temporaris")
->setTitle("Template Relevé des heures intérimaires")
->setSubject("Template excel")
->setDescription("Template excel permettant la création d'un ou plusieurs relevés d'heures")
->setKeywords("Template excel");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', "12");
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="excel.xls"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
But it's Excel5 not Excel2007 and when i remplace Excel5 by Excel2007 i have the same error message.
Did you try this ?
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);

PHPExcel Force Download Issue

I know this might have been asked in several pieces, but I could not find an exact answer to the issue. I am using PHPExcel to generate an Excel file (obviously), and the code works to generate the file, but not when I include the code for Force Download, it corrupts the file. My latest version of the script looks like this:
function make_xls_spreadsheet(){
/** Error reporting */
error_reporting(E_ALL);
/* Set the save path */
define('XLSX_SAVE_PATH', 'tmp/');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
/** PHPExcel */
include 'PHPExcel.php';
/** PHPExcel_Writer_Excel2007 */
include 'PHPExcel/Writer/Excel2007.php';
/* Create a new PHPExcel Object */
$objPHPExcel = new PHPExcel();
/* Add some metadata to the file */
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
/* Set active worksheet to first */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Segments');
/* Add some data to the worksheet */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
/* Write to server */
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$filename = "tony1.xlsx";
// Works fine up to here
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->save('php://output');
$objWriter->save(XLSX_SAVE_PATH . $filename);
readfile(XLSX_SAVE_PATH . $filename);
echo "DONE!";
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
}
Remember, when I remove the force code section, the file generates and I can FTP it down fine. However, doing both generating and forcing the file gives me a corrupt file. Normally I can click "Open & Repair" (Office2011 MacOSX) but obviously this is not desirable.
Could someone please help me understand:
Why it is being generated as corrupt? And why it works fine when I don't force download.
What the proper order for saving/forcing is (using PHP's header() function)
If there is a better way of doing this.
Much appreciated!!
**** Update **** Here is the code when I click "Fix & Repair":
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>Repair Result to tony1 03178.xml</logFileName>
<summary>Errors were detected in file 'Macintosh HD:Users:tony.diloreto:Downloads:tony1.xlsx'</summary>
<additionalInfo><info>Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.</info></additionalInfo>
</recoveryLog>
// answer actually belongs to #Dagon
The answer is actually straightforward, only needing a simple exit(); call.
Final code block:
function make_xls_spreadsheet(){
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
/** PHPExcel */
include 'PHPExcel.php';
/** PHPExcel_Writer_Excel2007 */
include 'PHPExcel/Writer/Excel2007.php';
/* Create a new PHPExcel Object */
$objPHPExcel = new PHPExcel();
/** Determine filename **/
$filename = "tony1.xlsx";
/** Set header information **/
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
/* Add some metadata to the file */
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
/* Set active worksheet to first */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Segments');
/* Add some data to the worksheet */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit();
}
This spits out the excel file to the browser:
readfile(XLSX_SAVE_PATH . $filename);
and then you spit this out, which becomes PART of the excel file as downloaded by the browser
echo "DONE!";
essentially you're sending
[excel data]DONE!
when Excel is expecting only
[excel data]
Try to modify File.php like this :
protected static $_useUploadTempDirectory = TRUE;
in folder phpexcel/Classes/PHPExcel/Shared (it's not the best way but it worked for me).

How to save multiple file in phpexcel?

For example I have 5000 data.
I'm trying to split these data 1000 for each file in excel.
Saw this example :
Create two workbooks
($objPHPExcelFile1=new PHPExcel(); $objPHPExcelFile2=new PHPExcel();
so I did this
$jco=1; $jcos=1;
$trig=0; $rowNya = 2;
$no = 0;
if ($VinDB->num_rows($result) != 0)
{
while($line = $VinDB->fetch_array($result)){
if($trig ==0 )
{
$objPHPExcel[$jcos] = new PHPExcel();
$objPHPExcel[$jcos]->getProperties()->setCreator("Test")
->setLastModifiedBy("Test")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("result file");
$trig=1;
}
$no = $no +1;
if($jco <= 1000){
$objPHPExcel[$jcos]->setActiveSheetIndex(0)
->setCellValue("A$rowNya", $no)
->setCellValue("B$rowNya", #$line["NoTransaksi"])
->setCellValue("C$rowNya", #$line["Pesan"])
->setCellValue("D$rowNya", #$line["Jam"])
->setCellValue("E$rowNya", #$line["Alias"])
->setCellValue("F$rowNya", #$line["Nomor_hp"])
->setCellValue("G$rowNya", #$line["GroupKU"])
->setCellValue("H$rowNya", #$line["Report"])
->setCellValue("I$rowNya", #$line["Status"])
->setCellValue("J$rowNya", #$line["Token"]);
$rowNya = $rowNya + 1;
$jco++;
}
else{
$jco=1;
$trig=0;
$objPHPExcel[$jcos]->getActiveSheet()->setTitle('Simple');
$objPHPExcel[$jcos]->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Report_part'.$jcos.'.xls"');
header('Cache-Control: max-age=0');
$objWriter[$jcos] = PHPExcel_IOFactory::createWriter($objPHPExcel[$jcos], 'Excel5');
$objWriter[$jcos]->save('php://output');
$jcos++;
}
}
}
It worked for the first 1000 data there's a save button, but for the part 2 its not working. Can anyone help me. Here the screenshot:
Latest:
Ok so ..i cant upload multiple files to browser, so i just do multiple sheet and save it on my local disk, but how do i download it from my localhost/server
here's my code
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('/xampp/htdocs/sms/Report_'.$jcos.'.xls');
$file = 'sms/Report_'.$jcos.'.xls';
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Content-Length: '.filesize($file));
readfile($file);
You can't send multiple files to the browser. Save your workbooks to disk, pack them into one file (e.g. zip) and send this single file to the browser.
Edit
After your while loop you can add:
$zip = new ZipArchive();
$zip->open('/xampp/htdocs/sms/Reports.zip', ZipArchive::OVERWRITE);
$zip->addGlob('/xampp/htdocs/sms/Report_*.xls');
$zip->close();
Please have a look at the docs for more options.
at last:
$file = '/xampp/htdocs/sms/Reports.zip';
header('Content-type: application/zip'); // Please check this, i just guessed
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($file));
readfile($file);

PHPExcel output unreadable and no errors thrown

Hello I have the following code
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$exchange = $_POST['exchange'];
$jobchange = $_POST['estimate'];
$wpchange = $_POST['wp'];
$username = "----";
$password = "----";
$hostname = "----";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("----", $dbhandle) or die("Could not select examples");
$query = "SELECT * FROM btsec WHERE WP='$wpchange' AND Exchange='$exchange' AND Estimate='$jobchange'";
$result = mysql_query($query);
$acellnum = "3";
$bcellnum = "3";
$ccellnum = "3";
$dcellnum = "3";
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Section ID')
->setCellValue('B1', 'Length')
->setCellValue('C1', 'Status')
->setCellValue('D1', 'TM');
while ($row = mysql_fetch_array($result)) {
// Query
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A".$acellnum, $row['SectionID'])
->setCellValue("B".$bcellnum, $row['Length'])
->setCellValue("C".$ccellnum, $row['Status'])
->setCellValue("D".$dcellnum, $row['TM']);
$acellnum++;
$bcellnum++;
$ccellnum++;
$dcellnum++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// 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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
It is generating the excel file, but all it outputs is text similar to this
ÐÏࡱá;þÿ
Opening in a text editor reveals no obvious errors and the script returns none either. I'm trying to output this to an Excel 2007 compatible format. Does anyone have any idea why this is happening?
EDIT: May not be relevant but Excel throws an error that the format does not match the extension
// Save Excel 2007 file
#echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="sectionlist.xlsx"');
$objWriter->save('php://output');
This fixed it and made it work! ob_end_clean was the solution.
To solve this problem try :
header('Content-Type: 'application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="test.xlsx"');
header('Cache-Control: max-age=0');
and
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
ob_start();
$objWriter->save('php://output');
Try changing this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
to this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
Also, excel 2007 expects the file to be .xlsx so you should probably change that in your header statement.
My PhpExcel Library just stopped working properly.
The result excel file was all written with really weird characters.
This:
ob_end_clean();
was my solution too.
In recent PHP-versions PHPExcel stops working without any errors. Look in PHPExcel/Calculations/Functions.php at line 576: there is a break-command, which is not allowed by PHP. If you remove that line, all works as it should work.

PHP Excel file downloaded via browser not opened by MS-Excel/OpenOffice

PHPExcel's simple exmple is correctly working for me on my local machine setup. It is downloading .xlsx file and MS-Excel program happly opens it.
Now I copied this code to my WordPress plugin to allow Excel download from WordPress Admin section
if ( file_exists(CHECKIN_PLUGIN_DIR . '/lib/PHPExcel.php') ) {
ob_end_clean();
ob_start();
/** Include PHPExcel */
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel.php");
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel/Writer/Excel2007.php");
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("PHPExcel Test Document")
->setSubject("PHPExcel Test Document")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->save("/home/user/ExcelTests/test01.xlsx");
$objWriter->save('php://output');
exit;
}
?>
<div class="wrap">
....
But the file downloaded can not be opened by the excel, it says Different format than specified by the file extension.... and when opened shows bunch of hexa chars
PKU~AG�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� �QĿi!��K�
When I changed the code to save it as a file in hard disk, it can be opened without any issues.
if ( file_exists(CHECKIN_PLUGIN_DIR . '/lib/PHPExcel.php') ) {
ob_end_clean();
ob_start();
/** Include PHPExcel */
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel.php");
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel/Writer/Excel2007.php");
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("PHPExcel Test Document")
->setSubject("PHPExcel Test Document")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
/*
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
*/
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("/home/user/ExcelTests/test01.xlsx");
//$objWriter->save('php://output');
exit;
}
?>
<div class="wrap">
....
Same happend for Excel5 format too.
But the CSV downloaded via browser has no issues.
Any help?
Update
File downloaded vi browser is here
File saved to filesyestem is here
Found an additional line feed char 0A before PK in downloaded file when viewed in Hexa editor
I tried to remove that line feed using trim
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();
ob_start();
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
$ob_content = ob_get_contents();
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="export.xlsx"');
header('Cache-Control: max-age=0');
echo trim($ob_content);
exit;
But even after that 0A is there at the start of file.
This almost certainly means that you're outputting something additional to the content of the xls file, such as white spaces or a BOM header. Open the file in a text editor, and look for any whitespace characters such as tabs, spaces, new lines, etc at the very beginning (before the PK characters) or end of the file, or for any obvious PHP error messages in the file itself.
I use this code on my project and this works well:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
$objWriter->save('php://output');

Categories