PHPExcel Downloaded after remaining code execution stops? - php

I have a problem like when I download excel sheet after remaining code not executing. Please look below mentioned sample code.
$data[]=array('EANCODE'=>6161106690015,'ItemDesc'=>'Electrical hammer mill 15hp'
,'UnitDesc'=>'PIECES','qty'=>10);
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$object->getActiveSheet()->setCellValue('A1', "EANCODE");
$object->getActiveSheet()->setCellValue('B1', "Item Name");
$object->getActiveSheet()->setCellValue('C1', 'Units');
$object->getActiveSheet()->setCellValue('D1', 'Quantity');
$excel_row = 2;
foreach($data as $item)
{
$object->getActiveSheet()->setCellValue('A'.$excel_row, $item['EANCODE']);
$object->getActiveSheet()->setCellValue('B'.$excel_row, $item['ItemDesc']);
$object->getActiveSheet()->setCellValue('C'.$excel_row, $item['UnitDesc']);
$object->getActiveSheet()->setCellValue('D'.$excel_row, $item['qty']);
$excel_row++;
}
$store_name='Insertion Failed Records - '. date('d-m-Y').".xlsx";
header('Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$store_name.'');
header('Cache-Control: max-age=0');
$objWriter =new PHPExcel_Writer_Excel2007($object, 'Excel2007');
$objWriter->save('php://output');
echo "something else";
Output : Excel Sheet downloading but given echo statement not showing.

To output the XLS sheet to the page you are on, just make sure that page has no other echo's,print's, outputs.
As per my knowledge when we create and download or save file in any directory all echo content before this statement $objWriter->save('php://output'); is written in your file and after that statement, all part is skipped.

Related

Download Excel file using PHPExcel

I am trying to download excel file using PHPExcel, it's like it download the excel file nicely but the data in excel file is all crap.. it's not what i expected. I passed very basic methods to test my excel sheet data output.
here is the code i'am trying
else if($request->p['type'] == 'excel')
{
$report_type_name = "Graph Survey Report";
$ExcelReport = new ExcelApExport($sections, $group_definition, $questions, $sample_corrections);
$objPHPExcel = $ExcelReport->export($sets, $disp_filter);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; "
. escape_for_content_disposition("{$report_name} - {$report_type_name} - " . date("Y-m-d.H.i") . ".xls"));
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
also I make object here and call phpexcel methods here
public function export($Sets, $disp_filter)
{
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Offic excel Test Document");
$objPHPExcel->getProperties()->setSubject(" Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for XLS, generated using PHP classes.");
//echo date('H:i:s') . " Add some data\n";
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
return $objPHPExcel;
}
please can you suggest me why this crap data is showing up in my file instead of expected data.
thanks in advance
It needs basically
ob_clean();
before saving object.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
This is the writer for .xlsx files. (See: https://github.com/PHPOffice/PHPExcel/blob/develop/Examples/01simple-download-xlsx.php)
So the right header would be:
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; "
. escape_for_content_disposition("{$report_name} - {$report_type_name} - " . date("Y-m-d.H.i") . ".xlsx")); //.xlsX!
The writer for old .xls-files is:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
See: https://github.com/PHPOffice/PHPExcel/blob/develop/Examples/01simple-download-xls.php
I ran into this problem recently and found another post here that is very helpful if ur still having the problem after using ob_clean()
check this post

PHPExcel unknown characters

I've followed some tutorials and saw some people with same issue but I can't figure out how to put this working on my project.
Btw, I'm using CodeIgniter framework and I have Excel 2007 in my computer.
public function exportExcel(){
require(APPPATH . 'libraries/toExcel/PHPExcel.php');
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename=01simple.xls');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;
}
This is my code just for testings. Whenever I download the file generated by that function and try to open it is this what I get:
And when I click "Yes" I receive this:
Solved.
ob_end_clean();
ob_start();
$objWriter->save('php://output');
All php_excel changed Unknown Creator worksheet.
directory application/third_party/phpexcel/PHPExcel/DocumentProperties.php
changed line 43;
private $creator = 'Unknown Creator'; changed ↓
private $creator = 'your name';

Using fromArray, setWrapText, setAutoFilter cannot get \n multi new line in cell to display correctly in Excel5

I have the following code
$objPHPExcel->getActiveSheet()->fromArray($DATAARRAY, NULL, 'A1', true);
$HighestCol = $objPHPExcel->getActiveSheet()->getHighestDataColumn();
$HighestRow = $objPHPExcel->getActiveSheet()->getHighestDataRow();
$objPHPExcel->getActiveSheet()->getStyle('A1:'.$HighestCol.'1')->getAlignment()->setWrapText(true);
foreach($objPHPExcel->getActiveSheet()->getRowDimensions() as $rd) {
$rd->setRowHeight(10);
}
$objPHPExcel->getActiveSheet()->setAutoFilter(
$objPHPExcel->getActiveSheet()->calculateWorksheetDimension()
);
PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
foreach(range('A',$HighestCol) as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
->setAutoSize(true);
}
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myfile.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
From the above code, my $DATAARRAY contain some that have new line in some of the cell.
When open the Excel file, those cell that is suppose to have new line, require me to double click on the cell, in order to reflect the correct height.
May I know which part of my part I did wrong.
Thank you.
Below is the solution that I manage to find out. (just in case anyone need it)
Just change the line
$objPHPExcel->getActiveSheet()->getStyle('A1:'.$HighestCol.'1')->getAlignment()->setWrapText(true);
to this
$objPHPExcel->getActiveSheet()->getStyle('A1:'.$HighestCol.$HighestRow)->getAlignment()->setWrapText(true);

PHPExcel is not generating correct xls file

I am using PHPExcel in my project to generate a xls file of data coming from the database. I have downloaded the library of PHPExcel and using it in my PHP class as give below :
Class name : A.class.php
Path : inside a folder named "inc";
PHPExcel Lib folder : inside "inc" and relative to A.class.php
class A{
// code stuff
public function phpexcelgenerate()
{
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel.php';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="sam.xlsx"');
header('Cache-Control: max-age=0');
$objPHPExcel = new PHPExcel;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', "12");
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// This line will force the file to download
$writer->save();
}
// code stuff
}
This code is generating a xls file but that file is fully empty. I am thinking that I have included the files of PHPExcel in a wrong way in PHP classes. Could anyone tell me where I am doing wrong OR an example how can I do the same ?
You need to pass a filename to the save() method. Then read the contents of that files and echo to the browser.
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$writer->save("excel.xls");
readfile("excel.xls");
first of all you need to read the file:
// Read the file
$objReader = PHPExcel_IOFactory::createReader(Excel5);
$objPHPExcel = $objReader->load($fileName);
now get the data from db:
//get data
$details = $this->main_model->get_details()->row();
then assign the data to correct cells:
$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $i);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$row, $rec->eType);
at the end write the new file:
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');

PHPExcel file cannot open file because the file format or file extension is not valid

I'm stuck with this problem, it's not displaying the actual excel file. Please check my code below:
/** Error reporting */
error_reporting(E_ALL);
/** PHPExcel */
require_once 'PHPExcel.php';
include 'PHPExcel/Writer/Excel2007.php';
// Create new PHPExcel object
#echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();
$excel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Payroll");
if(!$result){
die("Error");
}
$col = 0;
$row = 2;
while($mrow = mysql_fetch_assoc($result)) {
$col = 0;
foreach($mrow as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Scholar Id')
->setCellValue('B1', 'Lastname')
->setCellValue('C1', 'Middlename')
->setCellValue('D1', 'Firstname')
->setCellValue('E1', 'Barangay')
->setCellValue('F1', 'Level')
->setCellValue('G1', 'Allowance')
->setCellValue('H1', 'Has claimed?');
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(14);
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()- >setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->setShowGridlines(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->applyFromArray(
array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'FFFF00')
)
)
);
// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
#$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="payroll.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
I got it working now! Thanks to this phpexcel to download
I changed the code to this:
// Save Excel 2007 file
#echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="payroll.xlsx"');
$objWriter->save('php://output');
I think this line:
ob_end_clean();
solved my problem.
I don't know if i can help i had the same problem and i solved with
ob_end_clean();
i put it just after
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
So don't change the header and save it as xslx anyway, the problem is the buffer!
The most likely culprit if this is a cut-and-paste of your script is the
echo date('H:i:s') . " Write to Excel2007 format\n";
If you're sending to the browser for download, then there must be no other output (echoes, print statements, dropping in and out of PHP) than the output generated to php://output by PHPExcel itself
Please make sure that all files (e.g. that are included) are in UTF-8 without BOM encoding.
You can identify this in different ways, e.g. see this link.
Only if you need UTF-8 with BOM - please use ob_end_clean(); before data outputing to browser, as pointed in other answers here.
I have the same problem, the problem is simple. Just put code below :
ob_end_clean();
after :
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
i think the solution of this problem is the same as here:
Google Chrome errors while exporting XLS file using PHP
just add a space between attachement; and filename, that way :
header("Content-Disposition: attachment; filename=\"Past_Due_Report.xls\"");
as i can see in your own answer that's what you did, and is probably what fixed your problem.
I had the same problem but calling ob_end_clean() didn't work. My CMS (drupal 7) had messed up my headers so I got a new line (hex 0A) at the beginning of the content even if I called ob_end_clean() before the file output.
With the code below I finaly got rid of the leading new line:
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
ob_clean();
This answer save my life. Thanks #ARN
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="export_result.xlsx"');
for ($i = 0; $i < ob_get_level(); $i++) {
ob_end_flush();
}
ob_implicit_flush(1);
ob_clean();
$objWriter->save("php://output");
I have the same problem, but i using library phpspreadsheet
just put this function:
ob_end_clean();
after this code :
$writer = new Xlsx($spreadsheet);

Categories