phpexcel to download
Instead of saving it to a file, save it to php://output
Docs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// 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="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
PHPExcel - instead of downloading save it to the directory
- Remove all
header()
's - Use full path's: e.g
/home/database/public_html/application/mail/
- Cron job: Remove
if (PHP_SAPI == 'cli') die('This example should only be run from a Web Browser');
because this line of code checks if script is "called" by server(cgi-fcgi) or user(cli).
After that, you can use cron jobs or similar (if sever trying to run .php script).
If you trying to reach link trough web browser, you must use headers because headers
talk with browser.
PHPExcel download file, excel file hieroglyphics
The PK at the begining gives away it's a zip
file. Coincidentally, xlsx
is a special kind of zip
file. Try to save the file as .xlsx
instead of .xls
and Excel should handle it correctly.
Given you're specifying Excel2007
as the format, you're getting an .xlsx
file. If you need a .xls
file, maybe you can use Excel2003
instead.
phpexcel - Making file to download rather than saving in the server
You should have this in your code.
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
in addition to the code your provided for the file download.
You your code will be
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("Jobin Jose");
$objPHPExcel->getProperties()->setLastModifiedBy("Jobin Jose");
$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 PHPExcel classes.");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$gdImage = imagecreatefromjpeg('http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg');
// Add a drawing to the worksheetecho date('H:i:s') . " Add a drawing to the worksheet\n";
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('Sample image');
$objDrawing->setDescription('Sample image');
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setHeight(150);
$objDrawing->setCoordinates('C1');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
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;
PHPExcel download file
I have found a solution to download using AngularJS with ability to change the filename on the fly. We will need to download FileSave.js and include in the header of index.html. The code snippet is as below:
main.js
$scope.fetchReport = function(){
$http({
url: 'path_to_php_file',
method: 'POST',
responseType: 'arraybuffer',
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).success(function(data){
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
saveAs(blob, file_name_to_be+'.xlsx');
}).error(function(){
//Some error log
});
}
index.html
<button class="btn btn-primary" ng-click="fetchReport()">Get Report</button>
php file is same as in the question, just need to add a few lines before exit;
header('Content-disposition: attachment; filename='.$filename);
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//Replace php://output with $filename and add code below after that(before exit;)
readfile($filename);
Note: It's only for HTML5 suppported browser.
Related Topics
Php.Ini Is Nonexistent Loaded Configuration File (None)
JSON_Encode Function: Special Characters
Export MySQL Database Using PHP
Can You Add an If Statement in Order By
PHP Default Function Parameter Values, How to 'Pass Default Value' for 'Not Last' Parameters
Iterate Over Each Line in a String in PHP
Uploading File in PHP Server from Android Device
Executing a Shell Script in Background with PHP
Move_Uploaded_File() Function Is Not Working
Laravel Socialite: Invalidstateexception
How to Get the Total Number of Rows of a Group by Query
Upload 1Gb Files Using Chunking in PHP