I have a webpage that has a radio group as the options for the file format you wish to save. Options are:
.xls
.xlsx
.csv
All work but the .csv as it also adds the page HTML to the bottom of the file.
Here is what I'm trying (code snippets to show functionality):
// Creating the format
$data = $this->getQueryResults();
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle("Report");
$objPHPExcel->getProperties()->setCreator("me");
$objPHPExcel->getProperties()->setLastModifiedBy("me");
$objPHPExcel->getProperties()->setSubject("Report Stuff");
$objPHPExcel->getProperties()->setDescription("Report Stuff");
// Next I iterate through the data array
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
// check the radio option selected for the file format
if($this->radioXLS->Checked) {
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
header('Cache-Control: max-age=0');
}
if($this->radioXLSX->Checked) {
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$excel_name.'.xlsx"');
header('Cache-Control: max-age=0');
}
if($this->radioCSV->Checked) {
ob_end_clean(); // add/removing this does nothing
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->setDelimiter(',');
$objWriter->setEnclosure('');
$objWriter->setLineEnding("\r\n");
$objWriter->setSheetIndex(0);
ob_end_clean(); // add/removing this does nothing
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="'.$excel_name.'.csv"');
header('Cache-Control: max-age=0');
}
$objWriter->save('php://output');
Any thoughts as to why it appends the page HTML to the .csv file?
On a side note this is a Prado project if that matters
UPDATE:
A little more...
I have a webpage that generate a report in a tablature format (Think table/grid). On the same page I have the option to save the date in the tablature format to an Excel .xls (somehow .xlsx is not working now, ugh...). The user has the option to save the file in .xls .xlsx .csv, when clicked the file downloads from that page.
Would this cause the webpage already rendered to be added to the output via: php://output?
UPDATE - Solution:
Yep after looking at the excel files it's also adding the webpage HTML. I have also looked at the output buffer PHP functions but still nothing is working
while(ob_get_level() > 0) {
ob_end_clean();
}
if($this->radioCSV->Checked) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="'.$excel_name.'.csv"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->setDelimiter(',');
$objWriter->setEnclosure('');
$objWriter->setLineEnding("\r\n");
$objWriter->setSheetIndex(0);
} elseif($this->radioXLSX->Checked) {
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="'.$excel_name.'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
} else {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
}
$objWriter->save('php://output');
exit();
Writing to php://output is exactly the same as doing a plain echo statement. The output of $objWriter->save() will be added to everything else that's echoed or lies outside PHP blocks (<?php ... ?>).
An example:
This is right:
<?php
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle("Report");
// ...
$objWriter->save('php://output');
?>
This is wrong:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="es">
<head><title>Export to Excel</title>
</head>
<body>
<?php
echo '<h1>Export to Excel</h1>';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle("Report");
// ...
$objWriter->save('php://output');
?>
</body>
</html>
Have you verified that the Excel files don't contain the HTML? They might just be ignored by Excel. Does adding exit(); after the last line change anything?
Related
I use latest PHPExcel library for creating .xls, .xlsx files. When i try to output created file like this:
ob_end_clean();
$file = 'test.xls';
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
$objPHPWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objPHPWriter->setIncludeCharts(TRUE);
$objPHPWriter->save('php://output');
exit;
everything is fine until I try to create and output any charts. So i changed my code according to example:
ob_end_clean();
$objPHPWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objPHPWriter->setIncludeCharts(TRUE);
$objPHPWriter->save(str_replace('.php', '.xlsx', __FILE__));
exit;
This is working, but the file is not downloaded. So i modified code to output created file:
ob_end_clean();
$file = 'test.xlsx';
header('Content-Type: Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
$objPHPWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objPHPWriter->setIncludeCharts(TRUE);
$objPHPWriter->save('php://output');
exit;
And this is not working, ends up with ERR_INVALID_RESPONSE.
Also when i store excel file with charts with second code block, it's not compatibile with MS Excel 2016. It says the file is corrupted and the data were replaced or deleted. What am I missing? Thanks a lot.
I figured out one simple solution, first step is to store created .xlsx file, second is to download file with header("Location:"). Redundant files are deleted with array_map function.
array_map('unlink', glob( __DIR__."/*.xlsx"));
$file = 'test.xlsx';
$objPHPWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objPHPWriter->setIncludeCharts(TRUE);
$objPHPWriter->save($file);
header("Location: $file");
I cant save file generated by PHPExcel to server. When do it
$this->load->library('Classes/PHPExcel');
$this->phpexcel->getActiveSheet()->setCellValue('A5','Value');
more excel code...
$writer = new PHPExcel_Writer_Excel5($this->phpexcel);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="newFile.xls"');
header('Cache-Control: max-age=0');
$writer->setPreCalculateFormulas(false);
$writer->save('php://output');
I can download the file, but I tried many different ways to save the file in the server folder, for example
$filename = 'file.xls';
$writer = new PHPExcel_Writer_Excel5($this->phpexcel);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="newFile.xls"');
header('Cache-Control: max-age=0');
$writer->setPreCalculateFormulas(false);
$writer->save($filename);
or use PHPExcel_IOFactory to save the file, but I cant get it to work, same idea pliss.
regards.
try this :
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fname.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('./files/'.$fname);
Last night I solved the error.
$writer = new PHPExcel_Writer_Excel5($this->phpexcel);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="newFile.xls"');
header('Cache-Control: max-age=0');
$writer->setPreCalculateFormulas(false);
$writer->save(getcwd().'/mailAttachment/newFile.xls');
I add this line.
$writer->save(getcwd().'/mailAttachment/newFile.xls');
the function getcwd() get the current working directory.
Thanks anyway.
<?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}
);
}
);
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');
I have some problem with PHPExcel where it keep throws couldn't reading (generated) file, here's the code:
include 'PHPExcel/PHPExcel.php';
$rtype = $_REQUEST['rtype'];
// set headers to redirect output to client browser as a file download
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report_'.$rtype.'.xls"');
header('Cache-Control: no-cache');
header('Pragma: no-cache');
header('Expires: 0');
//-----Create a reader, set some parameters and read in the file-----
$objReader = PHPExcel_IOFactory::createReader('CSV');
$objReader->setDelimiter(',');
$objReader->setEnclosure('');
$objReader->setLineEnding("\r\n");
$objReader->setSheetIndex(0);
$objPHPExcel = $objReader->load('db_report.php?rtype='.$rtype.'&type=csv');
//-----Create a Writer and output the file to the browser-----
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
already checked db_report.php and it output a csv file, so nothing wrong for this file
You try to load String value 'db_report.php?rtype='.$rtype.'&type=csv' is it not url.
Load first data ex:
$data = file_get_contents('http://domen.com/db_report.php?rtype='.$rtype.'&type=csv');
$objPHPExcel = $objReader->load($data);