PHPExcel......spreadsheet displays on webpage instead of downloading - php

<?php
if($_POST['export'])
{
require_once (dirname(__FILE__) . '/../Classes/PHPExcel.php');
$qry="select accessed_Menus as menus,phone_number as phone,date_Accessed as timeAxed,sessionid as sessiondetails from access_trails where DATEADD(dd, 0, DATEDIFF(dd, 0 ,date_Accessed)) >= DATEADD(dd, -10, DATEDIFF(dd, 0, {fn NOW()})) order by date_Accessed desc";
$result=mssql_query($qry);
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
while($row =mssql_fetch_assoc($result)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['menus']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['phone']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['timeAxed']);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $row['sessiondetails']);
$rowCount++;
}
$objPHPExcel->getActiveSheet()->setTitle('Access Logs');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Access logs.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
Hi guys.....am using the code above to export data from a database to a spreadsheet....i able to retieve the data right but it only displays inside the loaded page. Am able to download a .xls file from my localhost though. Help

You can try adding these two headers, though I'm unsure it will help (I didn't tested it):
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: Binary");

Besides what's been pointed out you could also try adding these to the headers:
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
Even though they don't seem to be needed for file to be prompted to download (the example I tried only has the same lines your code shows and it downloads without a problem in both IE 10 and Chrome)

Php Code
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=export.xls");
header("Content-Transfer-Encoding: binary ");
echo strip_tags($_POST['tableData'],'<table><th><tr><td>');
Then use the javascript below to export
$(function()
{
$("#exportToExcel").click
(function()
{
var data='<table>'+$("#ReportTable").html().replace(/<a\/?[^>]+>/gi, '')+'</table>';
$('body').prepend("<form method='post' action='php/exporttoexcel.php' style='display:none' id='ReportTableData'><input type='text' name='tableData' value='"+data+"' ></form>");
$('#ReportTableData').submit().remove();
return false;
d}
);
}
);

Related

PHPexcel html to excel with images

I write code like this:
require_once(VENDOR . 'phpexcel/PHPExcel/Classes/PHPExcel.php');
$objPHPExcel = new \PHPExcel();
$xlsxname = WWW_ROOT.'excelexport/kontrahent-'.$q->id_kontrahent.'.xlsx';
$table = '<table>'.$_POST['print'].'</table>';
// print_r($_POST);
$file = WWW_ROOT.'NowExcelExport.html';
// Open the file to get existing content
$current = $table;
file_put_contents($file, $current);
$filename = 'excelexport/kontrahent-'.$q->id_kontrahent.'.xls';
// $table = $_POST['table'];
ini_set('zlib.output_compression','Off');
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");
//the folowing two lines make sure it is saved as a xls file
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
$objReader = \PHPExcel_IOFactory::createReader('HTML');
$objPHPExcel = $objReader->load($file);
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Okey, now I input to this code, a html code. This code have images .png/.jpg etc. Export works fine but in my excel files not showing images. Do you have any idea how I can export images?

not able to download or open blank PDF file PHP

I am facing some problems while generating PDF reports from my application in firefox(ubuntu machine).
my code is:
<?php
$path = "path_to_file" ;
$file = "test.pdf";
header('Content-type: application/pdf');
header("Content-disposition: attachment; filename=$file");
readfile($path);
return new Response("Success");
code is working:
when the PDF-report contains data
when size is more than 1 kb
In windows machine
not working:
when report contains no data or size is in bytes.
It is Generating a binary sting in a new tab in browser instead of generating blank-PDF.
Please help me fixing this issue.Thanks in advance.
Got my answer.This may help others.
<?php
$path = "path_to_file" ;
$file = "test.pdf";
header("Content-disposition: attachment; filename= $file"); //Tell the filename to the browser
header("Content-type: application/pdf");//Get and show report format
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
readfile($path); //Read and stream the file
get_curret_user();
I would do it in this way to avoid some problems with browser applications and caching. Give it a try:
<?php
$path = "path_to_file" ;
$file = "test.pdf";
$content = file_get_contents($path);
header("Content-disposition: attachment; filename=\"".$file."\"");
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($content));
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: 0");
echo $content;
die();
EDIT:
If it's really necessary to use the pdf plugin of the browser instead of downloading and opening it immediately with the associated default pdf reader, please replace
header("Content-type: application/force-download");
with
header("Content-type: application/pdf");

Header file download creates new file instead of sending one from server (PHP)

I have the following code in an attempt to have it so a specific file on the server is downloaded:
$file = 'upload/Order.txt';
header("Pragma: public", true);
header("Expires: 0"); // set expiration time
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="basename.$file);
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
All that happens is it causes the browser to download a file, in my case "Order.txt", but its blank, it is just creating this file out of no where. It doesn't do anything with the "upload/" path portion of $file.
Thanks for any help, I find headers really confusing, why I can't just have "download ($file)" is beyond me.
Edit: I'll struggle over a problem for days, finally decide to ask here then immediately after fix it my self.
I changed the location of the file to be in the same as the PHP script, I'd still like to know how to make it work with them being separate however. I also added:
readfile($file);
If I alter with of these 2 changes it doesn't work.
Also slim lined it, new code:
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
you should print content of file to stdout after headers:
$file = 'upload/Order.txt';
header("Pragma: public", true);
header("Expires: 0"); // set expiration time
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=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);
echo $contents;
Try change this line:
header("Content-Disposition: attachment; filename='".basename($file)."';");

In php Instead of downloading csv file it gets open in the browser

I'm trying to download a CSV file through the browser. The script is partially working, because so far I managed to display the CSV on screen, but the download is not starting.
Here is what i tried so far:
if(isset($currency)) {
header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=Pricelogs.csv");
ob_clean();
$filename = "/tmp/".uniqid().".csv";
exportCSVFile($filename, $currency, $country, $provider);
readfile($filename);
//unlink("'".$filename."'");
} else {
echo "ERR_USERNAME_PASSWORD";
exit();
}
I had already read all questions of this type from FAQ & also tried but it gets open on browser only,instead of downloading.
I had also used header with single quotes.
I also tried header("Content-Type: text/csv");
Also:
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");
PUT your CSV file URL, it will display in browser in place of force browser to download. You can open it in iframe in your site.
http://docs.google.com/viewer?embedded=true&url=www.yoursite.com/filename.csv
I usually just do:
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=my_csv_filename.csv");
// print CSV lines here
exit();
I can tell you this combination is working for me:
$bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
header("Content-type: application/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
print $bom . $data;
exit;
If I were you, I would first test this plainly (outside of all your buffering), first see that you manage to make this work, and only then test it in your specific set up.
You might try this.
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: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
print $content;
For large files you need to get your output buffer started
add : ob_start(); at the start
ob_clean(); at the end of you file

Stream binary file from MySQL to download with PHP

I have Excel spreadsheets stored in a MySQL table longblob field. I need to retrieve this data and then stream it to the user as a downloadable file, preferably without writing it to disk first.
Possible?
Edit - Eh, just figured it out... Posted in answer below.
function getfile($blockid)
{
global $msa_db;
$sql = "select filename, filedata from blocks where blockid = '$blockid'";
$query = mysql_query($sql, $msa_db);
$result['filename'] = mysql_result($query,0,0);
$result['filedata'] = mysql_result($query,0,1);
return $result;
}
function download($fileinfo)
{
$file = base64_decode($fileinfo['filedata']);
header("Cache-Control: no-cache private");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.$fileinfo['filename']);
header("Content-Type: application/vnd.ms-excel");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. strlen($file));
echo $file;
exit;
}
$fileinfo = getfile($blockid);
download($fileinfo);
Just got the solution
http://www.codeproject.com/Articles/831185/CREATE-DOWNLOAD-ZIP-FILE-USING-PHP
$data = base64_decode($data);
header("Cache-Control: no-cache private");
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename='".$identifier.".zip'");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. strlen($data));
header("Pragma: no-cache");
header("Expires: 0");
ob_clean();
flush();
echo $data;

Categories