I am facing problem with PHPExcel excel download code.A download code which is working on one server (netcore server) but same set of code not working on AWS server.can any one help me to figure out what could be the exact issue?? following is the phpexcel download code :
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');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
// 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");
// 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);
// 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');
Excel file is downloaded but with Junk/Un-supported characters
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�
I ran into this exact problem while doing an xlsx file and found that it was a buffer issue. To solve it I used the php output control function ob_end_clean(); right before save. So in your case it would look like:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
$objWriter->save('php://output');
I had the same problem.
ob_end_clean(); $objWriter->save('php://output');
This will remove unwanted characters from excel.
I've faced the same problem
you can try this format
require_once './application/Classes/PHPExcel/IOFactory.php';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); //Excel2007
ob_clean();
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-type: application/x-msexcel; charset=utf-8");
header('Content-Disposition: attachment;filename="Filename.xls"');
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
$objWriter->save('php://output');
Related
I am trying to download excel file generated by phpexcel. I am using example "Simple download xlsx" of phpexcel.
I am using same concept given in this SO question.
I am calling php file by POST request from client. Not passing any header. Using below code:
MessageService.invokePostRequest(
"/rest/testphpexcel1.php",
function(returnedResponse){
var data_type = 'application/vnd.ms-excel';
var excelDoc = new Blob([returnedResponse], {
type: data_type
});
var url = window.URL.createObjectURL(excelDoc);
var exportLink = new core.Element('a');
exportLink.setAttribute('href', url);
exportLink.setAttribute('download', this.filename + '.xlsx');
exportLink.trigger('click');
//adding some delay in removing the dynamically created link solved the problem in FireFox
setTimeout(function() {
window.URL.revokeObjectURL(url);
}, 0);
}.bind(this),{data: JSON.stringify(postData)}
Here MessageService.invokePostRequest is a wrapper around ajax.
On server side I've below php 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");
// 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');
// 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 (Excel2007)
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Here I tried with Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet on client and server both side.
I am getting below response headers (from chrome's developer tools):
cache-control:must-revalidate
connection:Keep-Alive
content-disposition:attachment;filename="01simple.xlsx"
content-length:6309
content-transfer-encoding:binary
content-type:text/html; charset=UTF-8
date:Fri, 30 Jun 2017 13:51:40 GMT
keep-alive:timeout=5, max=100
pragma:public
server:Apache/2.4.6 (CentOS) PHP/5.4.16
x-powered-by:PHP/5.4.16
From content-length I assume there is some data and in response tab I can see some gibberish text. But that response is not properly converted to excel file, I think.
A file is always getting downloaded and when I open the file, it has text "Unexpected token P in JSON at position 0".
I don't know what am I doing wrong here.
How to download a proper excel file generated by phpexcel ?
Try to use additional headers, it works for me. And try to open by php without js. If php opens correct, try to find error in js script.
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');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
I am trying to create and download excel file using PHPExcel in my CakePHP 1.3 application, But its not working.
My code:-
App::import('Vendor', 'PHPExcel', array('file' => 'Classes/PHPExcel.php'));
$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");
// 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', 'Miscellaneous glyphs');
// 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;
No error is coming while downloading. It just downloading a blank file.
It is working (creating and downloading properly) in core PHP but not working in CakePHP 1.3.
step1: Download from (http://www.codeplex.com/PHPExcel) and place it under app\vendors\Classes. Also make sure you place file containing class PHPExcel out side the directory. so your classes directory will have 1 folder and one file.
step2: create a CSV file in view page in the location views/view_name/csv.
step 3: Inside this folder create a file.
e.g.
<?php
echo "ID, Property ID, Date, Status \n";
foreach($x as $y) {
echo $y['Incident']['id'] . ',';
echo $y['Incident']['name'] . ',';
echo $y['Incident']['date'] .',';
echo $y['Incident']['status'];
echo "\n";
}
Step4: Provide proper link in any view where you are calling.
Use the link:
https://stackoverflow.com/a/37072809/2281448
NB: The above answer is for CakePHP 2.0. But the only difference is in the folder structure which is given below.
Place the folder 'Classes' into your Cakephp folder 'app/vendors/PHPExcel'.
hello i am new to phpexcel,
and i was wondering if there is some way send the excel i have created to the clients download without saving it on my server or to delete it right after he downloads it
i am trying to create an "export button" on a page that will give the user a "pop-up" with the excel that he wants that i have just created.
now after i create the table i do :
$objXLS->getActiveSheet()->getColumnDimension("A")->setAutoSize(true);
$objXLS->getActiveSheet()->getColumnDimension("B")->setAutoSize(true);
$objXLS->getActiveSheet()->setTitle('Test Stats');
$objXLS->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objXLS, 'Excel5');
$objWriter->save(__DIR__."/test1.xls");
but that saves it to my server
thank you
Instead of saving it to a file, save it to php://outputDocs:
$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.
$excel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');
// Do your stuff here
$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
// This line will force the file to download
$writer->save('php://output');
Use this call
$objWriter->save('php://output');
To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.
FOR XLSX USE
SET IN $xlsName name from XLSX with extension. Example: $xlsName = 'teste.xlsx';
$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
FOR XLS USE
SET IN $xlsName name from XLS with extension. Example: $xlsName = 'teste.xls';
$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xlsx"');
header('Cache-Control: max-age=0');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
posible you already solved your problem, any way i hope this help you.
all files downloaded starts with empty line, in my case where four empty
lines, and it make a problem. No matter if you work with readfile(); or
save('php://output');, This can be fixed with adding ob_start(); at the
beginning of the script and ob_end_clean(); just before the readfile(); or
save('php://output');.
I tried the $writer->save('php://output'); command proposed by most answers.
But this happened to download a corrupted file.
To fix it, I had to do this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="filename.xlsx"');
header('Cache-Control: max-age=0');
$path = 'path/to/temp/file.xlsx';
// save content to temporary file
$objWriter->save($path);
// This header was key to me, in order to get it working
header("Content-Length: ".filesize($path));
// output file content
readfile($path);
// delete temporary file
unlink($path);
OK, now I read examples of phpexcel. As I understand there shouldn't be any other output on page, to make proper xls-file. I think so, because when I have
echo "some output and my form for query";
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Administrator");
$objPHPExcel->getProperties()->setLastModifiedBy("Administrator");
$objPHPExcel->getProperties()->setTitle("test");
$objPHPExcel->getProperties()->setSubject("test");
$objPHPExcel->getProperties()->setDescription("test");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// 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
echo"some other code";
And get xls, it has warnings that it doen't have css links there and moreover it puts a lot of text except Hello world!, such as links in excel file.
It looks like this:
I can put all work with xls in other php file and get it with ajax, but how can I give results of query to this file? All queries should be in my main file, because I don't want to have multiple connections to database. How it is clear, what I want. Any advices?
To download xls(x) file, you have to set right headers and clean the buffer to avoid bad stream.
As documentation explains you can try with this code:
//------------- Enter your code before this line --------- //
// Cleaning buffer
ob_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
/* Or you can use
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
*/
// redirect output to client browser
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_filename.xls"');
/* Use this for Writer Excel2007
header('Content-Disposition: attachment;filename="your_filename.xlsx"');
*/
header('Cache-Control: max-age=0');
//Start Download
$objWriter->save('php://output');
You can refer here for the Developers Documentation of PHPExcel
I use a file to build an array from a database, and I want to write to an excel sheet based on this array.
As such I include the file in the following code
(the code below is a complete copy paste of the code used to read from an excel template, edit the data, and write the file and prompt a download for the user)
/** Error reporting */
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');
/** PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("template.xls");
//HERE IS MY INCLUDE FILE
include($_SERVER["DOCUMENT_ROOT"] . "/includes/excelwrite_data.php");
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A2', 'TEST')
// 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');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
This generates a garbled excel file output, and warnings of corrupted data (similar to what happens when your php results in some echod character that messes it up. I have checked that my included file echoes nothing.
What is bizarre, is if I literally copy paste the contents of the included file into the spot where the include is in the above code, it works perfectly.
Is there something about includes that doesn't play well with PHPExcel?
Many thanks for your thoughts in advance.