download generated excel file on the fly after generation - php

I've created an excel file with phpexcel and successfully save it on the server. but what I really want to do is to say the browser to download this file on the fly. is there any solution for this?
here is my code :
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$col = 0;
foreach ($json[0] as $key => $value) {
$a = $key;
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $key);
$col++;
}
$row = 2;
foreach ($json as $itemGroup) {
$col = 0;
foreach ($itemGroup as $key => $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
$objPHPExcel->getActiveSheet()->setTitle('Report');
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
try {
$fileName = date("Y-m-d H:i:s");
$objWriter->save('/uploaded_images/generatedReports/' . $fileName . '.xlsx');
return true;
} catch (Exception $exc) {
return false;
}

Look at the example 01simple-download-xlsx.php which shows the headers to set and that you should save to php://output rather than to a "named" file

header('Location : /uploaded_images/generatedReports/' . $fileName . '.xlsx');

Tried with the attachment header ?
header("Content-Disposition: attachment; filename=your_file.xls");

Berofe returning true in try block you have to use header method for downloadable action
$filename ="excelreport.xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
echo "your content \t you next tabcontent \n your next line content \t"

You can set the appropriate headers, and use 'php://stdout' as the output filename.
e.g.
$filename = date("Y-m-d H:i:s").'.xls';
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
$objWriter->save('php://stdout');
return true;

Related

Create excel file without library

I using this code:
header( "Content-Type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=liste.xls");
echo "\xEF\xBB\xBF";
and I writing my SQL datas in a while loop like this:
echo "\n<table><tr><td>".$first[$post_a]."</td>\t<td>".$second[$post_a]."</td>\t<td>".$third[$post_a]."</td>\t</td></tr></table>";
When I try to open this created file, excel saying version and type are unmating even so I can open file after this warning on desktop but when I try to open on my phone file can't opening after warning.
You need to something like this here. Also ignore my logic in for-loop, may want to use your own.
$filename = "export_".date("m-d-Y_hia") . ".csv";
ob_end_clean();
$fp = fopen($filename,"w");
$is_header = true;
$no_meta_appnd = array('SKU','Name','Publish','Categories','Description');
foreach ($res as $index => $product){
$arr = array();
if($is_header){ // put all the header in array
foreach ($product as $index => $p){
if(in_array($index,$no_meta_appnd)){
array_push($arr,$index);
}else{
array_push($arr,"Meta: ".$index);
}
}
$is_header = false;
fputcsv($fp,$arr); // add headers
$arr = array(); // empty out array for first row
foreach ($product as $index => $p){
array_push($arr,$p);
}
fputcsv($fp,$arr); // add first row after header
}else{
foreach ($product as $index => $p){
array_push($arr,$p);
}
fputcsv($fp,$arr); // rest of the rows
}
}
//unserialize();
fclose($fp);
// download
// header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
header('Pragma: no-cache');
readfile($filename);
// deleting file
unlink($filename);
exit();

Trying to automatically open a dynamically generated CSV file from PHP script?

I'm successfully getting the desired output in console, but the browser isn't automatically downloading the CSV file.
header('Content-Type: application/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
$output = fopen('php://output', 'rb');
// output the column headings
fputcsv($output, array('Procedure Name', 'Totals'));
foreach ($rows as $row){
fputcsv($output, $row);
}
fopen($filename);
fclose($output);
A sample wich running in my browser:
$csv= '"Procedure Name", Totals'."\n";
$rows= array(
array('aaa', 'bbb'),
array('123', '456')
);
foreach ($rows as $row){
$csv .= implode(",",$row)."\n";
}
$filename= 'Totals Report for '.$name.' All-Time.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
die($csv);
Bah, this got unruly in the comments. I took it a step further and made it loop through the values too!
// Set headers
header('Content-Type: text/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
// Column titles
echo 'Procedure Name,Totals' . "\n"; // Don't forget the newlines!
// Data
foreach ($rows as $row) {
foreach ($row as $index => $value) {
echo $value;
if ($index < count($row) - 1) {
echo ',';
}
}
echo "\n";
}
You could also buffer it into a file so you can use fputcsv. That would work almost exactly as your current code, but at the end you'd have echo file_get_contents($the_buffer_file);
The main point is that all you need to do is output your data in CSV format, i.e. separate values by commas and a new line is a new row. It would also be smart to escape the values with quotation marks (not shown in my code).

instead of generating .xls file i am getting .php file on server side

I'm using following headers to generate excel file from database MySQL using PHP
header("Content-type: application/octet-stream");
header("Content-Type: application/vnd-ms-excel");
header("Content-disposition: attachments;filename=xxx.xls");
in localhost the output is xxx.xls which is correct file but in the server side i am getting xxx.php file (i am using a cpanel account for ftp)
guys please help me with a solution
simply use
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
Simply you can use the following php code.
You have to give an array with key value pair
$data = array("Name"=> "foo", "age" => 25);
$filename = "My File Name" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
foreach ($row as $value){
echo $value;
echo "\t";
}
echo "\n";
}
exit;

PHPExcel download file, excel file hieroglyphics

i have a problem to download excel file. When im saving on server its worked ok. But when i try to download things goes wrong.This is my code:
$result = getSoapResult($soapURL, $soapWSDL, $soapMETHOD, $inputParameters);
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header('Content-Disposition: attachment;filename="file_name.xls"');
header('Cache-Control: max-age=0');
$objExcel = new PHPExcel();
$objExcel->setActiveSheetIndex(0);
$rowCount = 1;
$column = 'A';
foreach($result as $key => $value){
if($rowCount == 1){
foreach($value as $k => $v){
$objExcel->getActiveSheet()->SetCellValue($column.$rowCount, $k);
$column++;
}
$rowCount++;
}
$column = 'A';
foreach($value as $k => $v){
$objExcel->getActiveSheet()->SetCellValue($column.$rowCount, $v);
$column++;
}
$rowCount++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
ob_clean();
$objWriter->save('php://output');
it gives an excel file with this content:
I cant find answer from another questions with this problem.
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.
Please add the code before your file download code
ob_end_clean();
ob_start();

How to change the filename of direct fopen output?

I am using this script to show a csv file:
if (isset($_GET['csv'])) {
header('Content-Type: text/csv; charset=utf-8');
$out = fopen('php://output', 'w');
foreach ($dataArray as $k => $v) {
fputcsv($out, $v);
}
fclose($out);
exit();
}
And this Javascript to open the csv for a direct download:
<a href="#" class="export" onclick="window.open(window.location.pathname + window.location.search + \'&csv=1\');">
Now I want to change the filename to something like:
subscriptions_2014_10_23.csv
Someone knows how to do so?
You need to add another header specifying the file name. Then throw in some date function to add into that:
$filename = 'subscriptions_' . date('Y_m_d') . '.csv';
header('Content-Disposition: attachment; filename="' . $filename . '"');
Just add one more header
header('Content-Disposition: attachment; filename=subscriptions_2014_10_23.csv');
maybe you should use header for file name :
header('Content-Disposition: attachment; subscriptions_2014_10_23.csv"');

Categories