PHPExcel Blank Screen - php

A lot of posts have been made on this particular case, I've gone through post on stackoverflow to ascertain why PHPExcel doesn't show a download dialog after exporting database data with the given code as shown:
// PHPExcel Code
$query = $this->reports_m->payreport_yr($yr,true);
if(!$query)return false;
$fields = $query->list_fields();
$this->excel->getProperties()->setTitle("Excel Export")->setDescription("Payment Report Excel Document");
$this->excel->getActiveSheet()->mergeCells('A1:D1');
//$this->excel->setActiveSheetIndex(0)->mergeCells('A1:D1');
//$this->excel->getActiveSheet()->getCell('A1')->setValue('This is the text that I want to see in the merged cells');
//$this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//activate worksheet number 1
$this->excel->setActiveSheetIndex(0);
$col = 0;
foreach ($fields as $field)
{
$this->excel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $headers[$field]);
$col++;
}
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($fields)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$this->excel->getActiveSheet()->getStyle($header_range)->getFont()->setBold(true);
$this->excel->getActiveSheet()->getStyle($header_range)->getFont()->setSize(16);
// Fetching the table data
$row = 2;
foreach($query->result() as $data){
$col = 0;
foreach ($fields as $field)
{
$this->excel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$this->excel->setActiveSheetIndex(0);
$filename=$yr.'taxPaymentReport.xlsx'; //Save The worksheet With This File Name
header('Content-Type: application/vnd.ms-excel'); //Mime Type For Excel2005
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel2007');
$objWriter->save('php://output');
I have tried changing the headers to see if i could get results but to no avail. Can someone with a better understanding tell me what am doind wrong?

Related

phpexcel library works fine on localhost but generates blank excel file in server

Here is my code that works fine in localhost to generate an excel file with data from database but in hosting server it generates a blank excel file:
// Starting the PHPExcel library
$this->load->library('PHPExcel');
//$this->load->library('PHPExcel/IOFactory');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
// Field names in the first row
$fields = $query->list_fields();
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
//format the column sizes
$sheet = $objPHPExcel->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells( true );
/** #var PHPExcel_Cell $cell */
foreach( $cellIterator as $cell ) {
$sheet->getColumnDimension( $cell->getColumn() )->setAutoSize( true );
}
//var_dump($query->result());
//die;
// Fetching the table data
$row = 2;
foreach($query->result() as $data)
{
$col = 0;
foreach($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
ob_clean();
$objWriter->save('php://output');
I think the problem is not related to phpexcel. I faced similar problem earlier and later found that CI's list_fields() function doesn't work in some linux server. You can check this aspect by placing field names statically instead of using this function.

PHPExcel Clone Worksheet - Efficient use of memory

I need to clone the first worksheet a few times, accordingly to the amount of rows, but something may be wrong.
The code is:
public function downloadFile()
{
date_default_timezone_set('America/Sao_Paulo');
if(file_exists("xpto.xlsx")){
$objPHPExcel = PHPExcel_IOFactory::load("xpto.xlsx");
$sheets = 3;//3 is enough to throw the error
for($i = 0; $i<$sheets; $i++){
$objClonedWorksheet = clone $objPHPExcel->getSheet(0);
$objClonedWorksheet->setTitle('Sheet ' . $i);
$objClonedWorksheet->setCellValue('A1', 'Test ' . $i);
$objPHPExcel->addSheet($objClonedWorksheet);
}
$objPHPExcel->setActiveSheetIndex(0);
$filename = 'file.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
$ret = $objWriter->save('php://output');
exit;
}
}
But I got an exhausted memory error. Than I tried the most commented solution (that is actually an workaround) that is to add
ini_set('memory_limit', '-1');
I added this line just after the load function and it worked, but I don't think it is a good solution to use on a SaaS application. I don't even think most hosts (AWS, for example) will allow me to use that.
I also tried to clone the sheet before the for loop, but when use addSheet, I realized that this function doesn't create a new object and when I change the name of the sheet (by the second iteration of the for loop), it changes the last sheet created, throwing an "already existing sheet with the same name" error.
Trying to use one of the links #rhazen listed, I changed the for loop to:
$objFromSheet = $objPHPExcel->getSheet(0);
$sheets = 3;
for($i = 1; $i<=$sheets; $i++){
$objToSheet = $objPHPExcel->createSheet($i);
foreach($objFromSheet->getRowIterator() as $row){
$cellIterator = $row->getCellIterator();
$cellFrom = $cellIterator->current();
$cellTo = $objToSheet->getCell($cellFrom->getCoordinate());
$cellTo->setXfIndex($cellFrom->getXfIndex());
$cellTo->setValue($cellFrom->getValue());
}
}
But it seems not to work either. Is there a misunderstanding about Iterator or XfIndex?
The solution is in the edited question. Thanks for those who helped.

Converting xlsx to pdf using PHPExcel and download that pdf . work Fine on localhost

This code works fine on localhost but on live server it shows
File Not Found
Check the file name for capitalization or other typing errors.
Check to see if the file was moved, renamed or deleted.
Here is my code
excel.php
<?php
error_reporting(1);
ini_set('display_errors', 0);
ini_set('display_startup_errors', TRUE);
$target = 'Myfile.xlsx';
include 'phpexcel/Classes/PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($target);
function datefix_excel($excel) {
$dif=(41885-$excel)*86400;
$seconds=1409737670-$dif;
$date=date("d/m/Y",$seconds);
return $date; }
//echo 'File ',pathinfo($inputFileName,PATHINFO_BASENAME),' has been identified as an ',$inputFileType,' file<br />';
//echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with the identified reader type<br />';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($target);
$i = 0;
$found = false;
try
{
//
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
//
//$objWorksheet = $objPHPExcel->getActiveSheet();
//now do whatever you want with the active sheet
$worksheet->setShowGridLines(false);
$worksheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER );
$worksheet->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER );
$worksheet->getPageSetup()->setFitToPage(true);
$worksheet->getPageSetup()->setFitToWidth(1);
$worksheet->getPageSetup()->setFitToHeight(0);
$worksheet->getPageSetup()->setScale(40);
$worksheet->getStyle('F1:F4')->getAlignment()->setWrapText(false);
$worksheet->getStyle('D6:D8')->getAlignment()->setWrapText(false);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$count = 0;
$found == false;
//
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($val==$_REQUEST['roll'])
{
//echo "Roll Number found: ".$_REQUEST['roll']." <br/>";
$found = true;
// $objPHPExcel->getActiveSheet()->setCellValue('C23',$val);
$objPHPExcel->getActiveSheet()->setCellValue('C23',datefix_excel($objPHPExcel->getActiveSheet()->getCell('C23')->getValue()));
$rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;
$rendererLibrary = 'dompdf';
$rendererLibraryPath = './' . $rendererLibrary;
//require_once (realpath(dirname(dirname(dirname(__FILE__))))."/libraries/pdf.php");
//echo $rendererName.' and '.$rendererLibraryPath;
if (!PHPExcel_Settings::setPdfRenderer($rendererName,$rendererLibraryPath)) {
die('NOTICE: Please set the $rendererName and $rendererLibraryPath values' .EOL .'at the top of this script as appropriate for your directory structure');
}
header("HTTP/1.1 200 OK");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;filename="rename.pdf"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->setSheetIndex($i);
//$objWriter->save('test.pdf');
$objWriter->save('php://output');
break;
}
else{
continue;
}
}
}
//
}
}
catch(Exception $e)
{
//echo $e;
}
?>
I would check: 1) is current folder writeable? 2) pdf.php is commented out, try enabling it (why? local machine probably has PDF installed, server does not), 3) try saving to file instead of outputting to browser, this will bypass any browser / security issues.

PHPExcel Set cell with variable

I have this test script that is acting just like my production script except production script pulls from a SQL db. I want to set the cell placement using a variable based off the count of an array. In the script below, (which you can copy and run as an example) I want to set the cell number based off how many of the same car that is in an array. So for an example there are 7 BMW's listed in the array. So I want the Comments: data copied to cell A12 using the code $num=$no+5; $cell='A'.$num;
The problem I am having is it does place it on that line but it also places it 7 more times about it. If there are 4 cars of that type it would place it on the right line but also place it 3 times above it. I just want it to place it once at the desired location. Any help would be great. Here is the code:
<?PHP
require_once 'Classes/PHPExcel.php';
include 'Classes/PHPExcel/Writer/Excel2007.php';
$dataArray= array();
$cars=array("Versa","Volt","Volt","Volt","Volt","Volkswagen","Bentley","Benz","BMW","BMW","BMW","BMW","BMW","BMW","BMW","Cobra","Cord","Daewoo","Datsun","Dodge","Dodge","Dixi");
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
while (list($var, $val) = each($cars)) {
if ($val!=$id){
$dataArray = array();
$objWorksheet = new PHPExcel_Worksheet($objPHPExcel);
$objPHPExcel->addSheet($objWorksheet);
$objWorksheet->setTitle(''. $val);
$row_array[$val] = $val;
array_push($dataArray,$row_array);
$no = count($dataArray);
$num=$no+5;
$cell='A'.$num;
$objWorksheet->setCellValue('A1' , $no);
$objWorksheet->setCellValue('A2' , $val);
$objWorksheet->setCellValue($cell , 'Comments:');
$id = $val;
}
else {
$row_array[$val] = $val;
$count=count($cars);
$count2=count($loc);
array_push($dataArray,$row_array);
$no = count($dataArray);
$num=$no+5;
$cell='A'.$num;
$objWorksheet->setCellValue('A2' , $no);
$objWorksheet->setCellValue('A3' , $val);
$objWorksheet->setCellValue($cell , 'Comments:');
$id = $val;
}
}
// 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');
// It will be called file.xls
header('Content-Disposition: attachment; filename="cars.xlsx"');
$objWriter->save('php://output');
Exit;
?>
This fixes the problem.
<?PHP
require_once 'Excel/PHPExcel.php';//path for my config, rewrite for yours
//include 'Classes/PHPExcel/Writer/Excel2007.php'; // not needed, lazy loader job
$cars=array("Versa","Volt","Volt","Volt","Volt","Volkswagen","Bentley","Benz","BMW","BMW","BMW","BMW","BMW","BMW","BMW","Cobra","Cord","Daewoo","Datsun","Dodge","Dodge","Dixi");
$objPHPExcel = new PHPExcel();
$objWorksheet=$objPHPExcel->setActiveSheetIndex(0);
$id='';
$countRows=0;
while (list($var, $val) = each($cars)) {
if ($val!=$id && $id!=''){
$objWorksheet->setTitle($id);
$num=$countRows+5;
$cell='A'.$num;
$objWorksheet->setCellValue($cell , 'Comments:');
$objWorksheet = new PHPExcel_Worksheet($objPHPExcel);
$objPHPExcel->addSheet($objWorksheet);
$id = $val;
$countRows=0;
}//end if
if($id=='') $id=$val;//the first car
$no = ++$countRows;
$objWorksheet->setCellValue('A'.$no , $no);
$objWorksheet->setCellValue('B'.$no , $id);//Versa, Volt, ...
}
if($countRows>0 && $id!=''){// the last car - if $id=='' the workbook is empty
$objWorksheet->setTitle($id);
$num=$countRows+5;
$cell='A'.$num;
$objWorksheet->setCellValue($cell , 'Comments:');
}//end if
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // note : use correct mime type (not xls for xlsx)
// It will be called cars.xlsx
header('Content-Disposition: attachment; filename="cars.xlsx"');
$objWriter->save('php://output');
Exit;
?>

Checkbox processing with PHPexcel Output

This my script...
$students=isset ($_POST['students']) ? $_POST['students'] : '';
for($i = 1; $i <= $students; $i++)
{
$student = isset ($_POST['student'.$i]) ? $_POST['student'.$i]: '';
$nilai= mysql_query ("SELECT * FROM student,s_semester where
student.id=s_semester.student_id_fk AND student.id='$student' GROUP by student.id");
$rowNya = 2;
$no = 0;
while ($data=mysql_fetch_array($nilai)) {
$no = $no +1;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A$rowNya", $no)
->setCellValue("B$rowNya", $student)
->setCellValue("C$rowNya", $data['idcard'])
->setCellValue("D$rowNya", $data['status']);
$rowNya = $rowNya + 1;
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
}
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="database_anggota.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
And my problem is, the excel output only one record of data that appears, i use checkbox before.. I check 3/4/5 or etc only 1 appears... If the output pdf and i use FPDF this script runnning well..
please help me...
Move $rowNya = 2; to before the for loop, otherwise it's being reset for each student id... otherwise you're resetting it to 2 after each student, so it'll overwrite the previous student details

Categories