PHPExcel can't save the file or download it - php

I'm trying to code a function in PHP to export some data to Excel file.
The problem is if I save it to the server it does work, but if I try to send to the browser using php://output it just doesn't work. It doesn't even show the download window. I' ve been getting these as response:
PK����a�B%���a��������[Content_Types].xml͔]K�0���%��f�
"�v��R���kX����׿�m��+����4�<�'��2�jgs6�,+��v����Sz���a�����tr5^�=Bb�9+c����,��9��.T"�kXr/�J,���[.��`ck6�?h�\��,���ܠ}3�c�C+��9�-E��|c�j�BKPN�+�d��u��O1�
o��Ba +���G�
The headers are:
Response Headers
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection Keep-Alive
Content-Disposition attachment;filename="Report.xlsx"
Content-Type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date Wed, 29 May 2013 10:08:10 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive timeout=15, max=78
Last-Modified Wed, 29 May 2013 10:08:11 GMT
Pragma no-cache
Server Apache/2.2.14 (Ubuntu)
Transfer-Encoding chunked
X-Powered-By PHP/5.3.2-1ubuntu4.19
Request Headers
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cookie PHPSESSID=075r4aaqrvcnbca5sshjvm0jq7; 87293ba76812d31889be0901b086dd73=5h4jriq5c7r9vdt3m2u2u9up43; d82d00149fafbe651c9ba75a9804bbc9=en-GB
Host 150.145.139.3:8889
Referer
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:20.0) Gecko/20100101 Firefox/20.0
X-Requested-With XMLHttpRequest
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/Rome');
require_once 'Classes/PHPExcel.php';
/** PHPExcel_IOFactory */
include 'Classes/PHPExcel/IOFactory.php';
$target ='templates/';
$fileType = 'Excel2007';
$InputFileName = $target.'richiesta.xlsx';
$OutputFileName = $target .'Richiesta_'.$_SESSION['User'].'_'.$_SESSION['Last'].'_'.$dat.'.xlsx';
//Read the file (including chart template)
$objReader = PHPExcel_IOFactory::createReader($fileType);
//$objReader->setIncludeCharts(TRUE);
$objPHPExcel = $objReader->load($InputFileName);
//Change the file
$objPHPExcel->setActiveSheetIndex(0)
// Add data
->setCellValue('C3','10' )
->setCellValue('C4','20' )
->setCellValue('C5','30')
->setCellValue('C5','40' );
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
//$objWriter->save($OutputFileName); //This one WORKS FINE!!!
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Report.xlsx"');
$objWriter->save('php://output'); //NOT WORKING :-(
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
exit;
I'm getting depressed about this problem once I have to finish the project this week.
I really appreciate any kind of help!

That's just from my code, as a hint, the problem seems to be with the Content-Type HTTP header:
if (strtolower($type) == 'excel2003') {
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $outFileName . '"');
header('Cache-Control: max-age=0');
} else {
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
header('Content-Type: application/xlsx');
header('Content-Disposition: attachment;filename="' . $outFileName . '"');
header('Cache-Control: max-age=0');
}

Try using these header() calls:
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=Report.xlsx");
header("Content-Transfer-Encoding: binary ");

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$filename = '1111';
ob_end_clean();
header("Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet");
header('Content-Disposition:attachment;filename="'.$filename.'.xlsx"');
header("Cache-Control: max-age=0");
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit();

I had the same problem, and it seems that a download must be opened in a different tab instead of just downloading in the same tab. Meaning you need to redirect into a new tab before initializing the download.

Related

export to csv via php does not work in firefox

I'm trying to fetch and download data using php to csv file, for task i found a good answer, this is working for me on all browser except firefox.
$s = $master->getUser();
function array2csv(array &$array)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
return ob_get_clean();
}
function download_send_headers($filename) {
/*header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename={$filename}");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies*/
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
download_send_headers(site_title .' '. date("d M Y") . ".csv");
echo array2csv($s);
die();
In Firefox file extension does not showing in csv, it is looking like application file.
Have you tried removing these in your code:
header("Content-Type: application/force-download");
header("Content-Type: application/download");
Just retain:
header("Content-Type: application/octet-stream");

export and download as csv in php not working in chrome and IE but working in firefox

I have a simple web page which pulls some data from DB and displays it in a html table and stores the data in some session variables.
I have a button "Export to csv" which calls a page which exports the results to a csv file.
The code for ExportToCsv file is:
<?php
session_start();
include "conn/sqlserverConn.php";
function download_send_headers($filename) {
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
$data = $_SESSION['data'];
$rows = $_SESSION['row'];
$header = $_SESSION['header'];
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
$file = fopen("php://output", 'w');
fputcsv($file,$header);
for($i=0; $i<$rows; ++$i)
{
$valuesArray=array();
foreach($data[$i] as $name => $value)
{
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
die();
?>
My code is working flawlessly in firefox but it is not working in chrome or IE. On chrome and IE it is showing error 404 (Object not found!). Please tell me what is the problem ?
As outlined in the blog article at: http://www.exchangecore.com/blog/php-output-array-csv-headers/, I tested the following and it worked in IE8-11, and in chrome version 34. I presume it will work in other browsers fine as well.
Headers to use:
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $fileName);

Displaying excel file in a browser. PHPExcel

For example I'm using such a code:
<?php
require_once("D:\server/www/cls/PHPExcel.php");
require_once("D:\server/www/cls/PHPExcel/IOFactory.php");
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', 'HeaderB');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', 'HeaderC');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', 'HeaderD');
ob_end_clean();
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="report.xlsx"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
$objWriter->save('php://output');
?>
It downloads report.xlsx file and doesn't display it in a browser. How do I make it?
Thanks!
Remove this line...
header('Content-Disposition: attachment;filename="report.xlsx"');
The user must have something in their browser capable of viewing the Excel file too.
comment this line
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="report.xlsx"');
replace also 'Excel2007' to 'html'
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'html');

PHP Excel Output for IE gives empty file

I am trying to generate an excel file with php. This works fine in Firefox but with IE I am only getting an empty file. This is what I am doing basically:
header('Content-type: application/ms-excel');
header('Content-Disposition: inline; attachment; filename='.$filename);
echo $data;
I have tried various header settings but no success. I have also tried to output the content as a text file, same result here. No content in IE.
Any ideas?
header("Cache-Control: no-stor,no-cache,must-revalidate");
header("Cache-Control: post-check=0,pre-check=0", false);
header("Cache-control: private");
header("Content-Type: application/octet-stream");
header('Content-Disposition: inline; attachment; filename='.$filename);
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
--
header('Pragma: public');
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header ("Pragma: no-cache");
header("Expires: 0");
header('Content-Transfer-Encoding: none');
header('Content-Type: application/vnd.ms-excel;');
header("Content-type: application/x-msexcel");
header('Content-Disposition: inline; attachment; filename='.$filename);
Just two Options, also tried some other combinations.
Thanks,
Roland
Had the same problem: IE times out after some short time if it doesn't get a response, even if the TCP connection is still open. What helped me was this: disable output buffering, send headers and flush them out. Send data when you have them. This was enough to keep the connection open.
Something like this:
// reset all output buffering
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Content-type: application/ms-excel');
header('Content-Disposition: inline; attachment; filename='.$filename);
// we can't send any more headers after this
flush();
$excel = new PhpExcel();
$excel->setActiveSheetIndex(0);
$sheet = $excel->getActiveSheet();
// in this example, $data was an array in the format row => value
// data structure is not relevant to issue
foreach ($data as $key => $value) {
// add data to sheet here
$sheet->SetCellValue('A' . $key, $value);
// etc...
}
$writer = new PHPExcel_Writer($excel);
// push to browser
$writer->save('php://output');
Set your header to header("Content-Type: application/octet-stream"); to force a download.
or another version of your header is adding vnd so application/vnd.ms-excel but if you send this header then you should also send your current header along side it as some browsers vary.

IE (HTTPS): generating pdf from php file doesn't work

Here is my issue. I am trying to call a page: foo.php?docID=bar and return a PDF to the screen which is stored as a BLOB in the DB.
Here is the portion of my code which actually returns the PDF:
$docID = isset($_REQUEST['docID']) ? $_REQUEST['docID'] : null;
if ($docID == null){
die("Document ID was not given.");
}
$results = getDocumentResults($docID);
if (verifyUser($user, $results['ProductId'])){
header('Content-type: application/pdf');
// this is the BLOB data from the results.
print $results[1];
}
else{
die('You are not allowed to view this document.');
}
This works perfectly fine in Firefox.
However, in IE, it doesn't show anything at all. If i'm on another page (i.e. google.com), and I type in the URL to go to this page, it will say it's done, but I will still have google.com on my screen.
I checked the headers for the responses from both firefox and IE. They are identical.
Does anyone have any suggestions? Need more information?
EDIT: If it helps at all, here's the response header and the first line of the content:
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 349930
Content-Type: application/pdf
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: PHP/5.1.2
Set-Cookie: PHPSESSID=cql3n3oc13crv3r46h2q04dvq4; path=/; domain=.example.com
Content-Disposition: inline; filename='downloadedFile.pdf'
X-Powered-By: ASP.NET
Date: Tue, 21 Apr 2009 16:35:59 GMT
%PDF-1.4
EDIT: Also, the page which pulls out the pdf file actually uses HTTPS instead of HTTP.
Thanks in advance,
~Zack
I figured out what the issue was. It's an IE bug dealing with IE, HTTPS and addons. (See here)
It was a caching issue. When I set:
header("Cache-Control: max-age=1");
header("Pragma: public");
(see here), the PDF was in cache long enough for the adobe reader add-on to grab it.
I had this issue too, i used the following which seems to work fine
header("Content-type: application/pdf");
header("Content-Length: $length");
header("Content-Disposition: inline; filename='$filename'");
Try this:
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=foo.pdf");
header("Accept-Ranges: bytes");
header("Content-Length: $len");
header("Expires: 0");
header("Cache-Control: private");
Also, if you are using sessions, you can try setting
session_cache_limiter("none");
or
session_cache_limiter("private");
if ( USR_BROWSER_AGENT == 'IE' ) {
header( 'Content-Disposition: inline; filename="' . $name . '"');
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Pragma: public' );
} else {
header( 'Content-Disposition: attachment; filename="' . $name . '"' );
header( 'Expires: 0' );
header( 'Pragma: no-cache' );
}
This was the only header I needed to change:
header("Pragma: public");
I think you need to add more headers.
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=THEFILENAME.pdf;");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($results[1]));

Categories