Phpexcel xls file showing garbage data while downloading - php

I am using PHPExcel 1.8.0 in my project. When I want to generate and download a .xls file with some data from my database, the file is downloaded with garbage data. Here is my code:
$result = mysql_query("select * from my_table");
ob_start();
//excel code
$this->load->library('excel');
//activate worksheet number 1
$this->excel->setActiveSheetIndex(0);
//name the worksheet
$this->excel->getActiveSheet()->setTitle('test worksheet');
$rowNumber = 5;
while ($row = mysql_fetch_assoc($result)) {
$col = 'B';
foreach ($fields as $cell) {
$this->excel->getActiveSheet()->setCellValue($col .$rowNumber, $row[$cell]);
$col++;
}
$rowNumber++;
}
// ob_end_clean();
// ob_clean() ;
$filename='report.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
exit();
I have used both ob_end_clean() and ob_clean() but nothing works.

Try this code:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
$objWriter->save('php://output');

Related

Error while opening generated excel file in php codeigniter using phpExcel

This how look generated excel file :
with the warning messages :
Message: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?
Filename: Shared/OLE.php
This is comes in excel file -
þÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ #€ÅfôíÖ#€ÅfôíÖþÿÕÍÕœ.“—+,ù®0¼HPX`hp
I have tried with iconv(mb_detect_encoding($result, mb_detect_order(), true), "UTF-8", $result); coversion as well.
This is the code :
public function exportExcel() {
$this->load->library('excel');
$registrationIDArr = $_POST["registrationID"];
$resigtrationIDStr = implode(",",$registrationIDArr);
$currDate = date("d-m-Y_H_i");
$file = 'VolunteerRegistration_'.$currDate.'.xls';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Volunteer Details');
$style = array('font' => array('size' => 12,'bold' => true));
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->applyFromArray($style);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Name');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Email');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
$rows = 2;
$result = $this->getVolunteerDetailsForExcelExport($resigtrationIDStr);
foreach($result as $row){
$objPHPExcel->getActiveSheet()->setCellValue('A'.$rows, $row->name);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$rows, $row->email);
$rows++;
}
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$file.'"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
ob_start();
$objWriter->save('php://output');
exit;
}
public function getVolunteerDetailsForExcelExport($registrationIDStr){
$this->db->select("CONCAT(fname,' ',mname,' ',lname) AS name, email");
$this->db->from('UserRegistration');
$wherelist = "id in($registrationIDStr)";
$this->db->where($wherelist);
$query= $this->db->get();
$result = $query->result();
return $result;
}
In PHPExcel/Shared/OLE.php,function _readPpsWks($blockId), there is an error in the for / switch structure.
In the default case of the switch, you write continue;. But this does NOT exit the for loop. It only exits the "switch" structure, and continue under. You have to write: continue 2;, at line number 290.
default:
continue 2;
Please try this, it might helps. This works for me.
require 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
/*CODE for excel*/
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="file.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

PHPExcel: Some Lines are not exporting in my .xls file while importing but shown when i echo the output?

I am using PHPExcel with mysql and MongoDB to export data in Excel .XLS file but only in 1 Column some Lines are not showing and some are showing in same Columns while exporting although all are shown when i use $print_() to check output in browser
Here is my PHP Code -
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValue('M1', 'Headline');
$objPHPExcel->getActiveSheet()->getStyle('M')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('M')->getFont()->setUnderline(true);
if ($result['type'] == "WEB") {
$sheet->setCellValue('M' . ($results + 2), $result['headline']);
$sheet->getCell('M' . ($results + 2))->getHyperlink()->setUrl($result['url']);
$sheet->getCell('M' . ($results + 2))->getHyperlink()->setTooltip('Navigate to website');
}
and this is my output
output
I post here an example without link (you can edit my code):
$objPHPExcel = new PHPExcel();
$result = $db->query("SELECT * FROM YOURTABLE") or die(mysql_error());
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('M1', 'Headline');
$objPHPExcel->getActiveSheet()->getStyle("M1")->getFont()->setBold(true);
$rowCount = 2;
while($row = $result->fetch_assoc()){
$objPHPExcel->getActiveSheet()->SetCellValue('M'.$rowCount, mb_strtoupper($row['headline'],'UTF-8'));
$rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="you-file-name.xlsx"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

PHPExcel Sum Function Yields to Corrupted Excel FIle

I am having issue for days now and couldn't figure out what's the issue. I appreciate any help. So, I am trying to put the total of a column in a cell in an excel file generated using phpexcel however the generated excel gets corrupted everytime I use the function SUM(). Function COUNT(), MIN(), etc. works just fine. The code is as follows:
foreach($data as $d)
{
$col = 0; $field_count = 0;
foreach($d as $cell)
{
$sheet->setCellValueByColumnAndRow($col, $row, $cell);
$col++; $field_count++;
}
$row++;
}
$sheet->setCellValue('E'.$row, 'Grand Total:' );
$sheet->setCellValue('F'.$row, '=SUM(F5:F'.($row-1).')');
//$sheet->setCellValue('G'.$row, '=COUNT(F5:F'.($row-1).')');
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
Here's the error I am getting everytime I use SUM:

PHPExcel : CodeIgniter error on output

I have this controller which renders my data from database to the PHPExcel library.
https://arjunphp.com/how-to-use-phpexcel-with-codeigniter/
this is my controller :
public function downloadTournamentData() {
$this->load->model("Tournament");
$var_data = array();
$var_data['tournament'] = $this->Tournament->getTournamentData();
$this->load->library('excel');
$this->excel->setActiveSheetIndex(0);
$this->excel->getActiveSheet()->setTitle('test');
$this->excel->getActiveSheet()->setCellValue('A1', 'member_username');
$this->excel->getActiveSheet()->setCellValue('B1', 'member_name');
$this->excel->getActiveSheet()->setCellValue('C1', 'member_phone');
$this->excel->getActiveSheet()->setCellValue('D1', 'member_email');
$this->excel->getActiveSheet()->setCellValue('E1', 'member_idcard');
$this->excel->getActiveSheet()->setCellValue('F1', 'Date_created');
$this->excel->getActiveSheet()->setCellValue('G1', 'team_name');
$this->excel->getActiveSheet()->setCellValue('H1', 'warnet_name');
$this->excel->getActiveSheet()->setCellValue('I1', 'warnet_cp');
$this->excel->getActiveSheet()->setCellValue('J1', 'warnet_phone');
$this->excel->getActiveSheet()->setCellValue('K1', 'region_name');
$this->excel->getActiveSheet()->setCellValue('L1', 'City');
$cell_inc = 2;
foreach($var_data['tournament'] as $k => $v) {
$this->excel->getActiveSheet()->setCellValue('A'.$cell_inc, $v['member_username']);
$this->excel->getActiveSheet()->setCellValue('B'.$cell_inc, $v['member_name']);
$this->excel->getActiveSheet()->setCellValue('C'.$cell_inc, $v['member_phone']);
$this->excel->getActiveSheet()->setCellValue('D'.$cell_inc, $v['member_email']);
$this->excel->getActiveSheet()->setCellValue('E'.$cell_inc, $v['member_idcard']);
$this->excel->getActiveSheet()->setCellValue('F'.$cell_inc, $v['Date_created']);
$this->excel->getActiveSheet()->setCellValue('G'.$cell_inc, $v['team_name']);
$this->excel->getActiveSheet()->setCellValue('H'.$cell_inc, $v['warnet_name']);
$this->excel->getActiveSheet()->setCellValue('I'.$cell_inc, $v['warnet_cp']);
$this->excel->getActiveSheet()->setCellValue('J'.$cell_inc, $v['warnet_phone']);
$this->excel->getActiveSheet()->setCellValue('K'.$cell_inc, $v['region_name']);
$this->excel->getActiveSheet()->setCellValue('L'.$cell_inc, $v['City']);
$cell_inc++;
}
date_default_timezone_set("Asia/Jakarta");
$this_date = date("Y-m-d");
$filename='pb_turnamen_data-'.$this_date.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel; charset=UTF-8'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
}
It does download the excel file. Only problem is that the data is mixed up and it's all wrong.
Why is this happening? Is there something wrong with my controller?
Please provide solution...
Add
ob_end_clean();
after
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
final code is
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
ob_end_clean();
$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