Error while generating an Excel file - php

I use the library PHPExcel for generating ".xlsx" files. The file is generated, but when I try to open it I get an error: Excel found some unreadable content. Do you want to fix the content? When I click on "yes" it opens my file with the content I want.
How can I avoid this error? I've already deleted all the spaces after the <?php ?> tags, I've already checked that I don't have HTML before the file is generated, but I still don't know where my error is.
Here is my code:
<?php
include ('/lib/PHPExcel/PHPExcel.php');
include ('/lib/PHPExcel/PHPExcel/IOFactory.php');
// I use session for now when the excel is generate
$_SESSION['downloadstatus'] = array(
"status" => "pending"
);
// Creation of the Excel File
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("Temporaris")
->setLastModifiedBy("Temporaris")
->setTitle("Template Relevé des heures intérimaires")
->setSubject("Template excel")
->setDescription("Template excel permettant la création d'un ou plusieurs relevés d'heures")
->setKeywords("Template excel");
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
// Add the content of Excel File
$indiceColumn = "A";
$indiceLine = 1;
$defaultColumns = array("Matricule", "Nom_Prenom", "Siret_etablissement", "Regate_etablissement", "Centre_analytique", "Date");
foreach ($defaultColumns as $columnName) {
$sheet->SetCellValue($indiceColumn . $indiceLine, $columnName);
$indiceColumn++;
}
$listColumnName = EDIXIS_db_query("select csv_nom_col FROM temporaris_eu_config_ent_csv WHERE id_config = " . $id_sel . " ORDER BY id");
while ($columnName = EDIXIS_db_fetch_object($listColumnName)) {
$sheet->SetCellValue($indiceColumn . $indiceLine, $columnName->csv_nom_col);
$indiceColumn++;
}
// Send the Excel File to the user
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="template.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
$_SESSION['downloadstatus'] = array(
"status" => "finished",
"message" => "Done"
);
?>
----- Edit -----
I try to check the difference between a repair file and the error file so i open them with notpad++.
Their is some caracters who are differents between the error file and the repair file :
some • who became «
some " who became « too
This line
‚›.›”Ò© +#SdÕ Eë ݲäÄfÃH*²?ÙÑý®³+ # î幜ᨽ]YC^!&íÝŒVSN 8é•v‹}œßOn(IY8%Œw0£kHô¶{×ÊÐHá{ôbÖ‚\jd˜ÑeΡa,É%X‘¦èp(>ûhEÆe\° ä‹X «9ÿÄ,d¡DlNÂHwH%ÈÐGS J20ÁåĪiÅŽÞѦ77åÄiu^xÓºîUÒã0ÓáºXñüûõðíg)u¢ÝØ* ´k•ld‘}ìæƒ"êÔ²“ÏcHù›ý¬A}YŸ9/ÕvWÜ– Šà¡šm {åéúîëüžv5¯>N8>æüsS󦮯xÝp>žàr¤Ú]Òÿa÷”Ò¬³R•Á,ò¯ìuCËúˆ/íò&j+4.Js¶;ƽè’Q‡Œsy$ÀJ‚!883ØéLŒ 2nÄè"ê}ïˆïI0}ÒÈO$–À„Ê6¯Dœ‚Ç Ôÿþ2ÿR¬{i¼ªX>ªtá;ÕÊoÚÂG¼/v¹:ûeº¿PK ”J¤Fs‘{Y³ ¦ xl/theme/theme1.xmlíYOoÛ6¿ïSº·²lÉu‚:EìØëÖ¦
who became this line
Ë7\ ÖIDiV´W¬„ +¸5ölkÖ;›ö‘ûLܺwH‘"çÇ3ž´·kgÙ32ÁÏy=­8¯‚6~9ç‹»ÉÎR–^K<Ìù¿í^µ*6* |óÄäS£âœ¯rŽI­ÀÉ4%‡'ñ1 “™–¸Qª'¹1«ª÷ÂA–Zf)Fà$‰|Ôꈌ=ÚÐJ€>'QOkqòf#—^ÜP”3§3yáEëA<º×ÉÃ0L‡›b¥ó×â×ý×¥Ô‰ñc«ð®ÕªQ2ìàb#‰&µâìóØB+S¾§f?П6ÎkµÝ·#€ft¨fWÂAùyóùËâŽw³ª~7©èy»¨>6³º©goªYSUã . 'ªÛ'ýö#)È&[(UYÊbßéÊž·LÓ°¬ GzŸ·hœ4´(ÍÙí÷’K¡‰™æòD€µËh>hf¨Ó™YÉnåèbúuïYèY´}2ÄOK"e—W"ÎÁcPêÿ•ÿ )Öƒ4^Õl†€:]ùεò[¶H÷%®W¿L÷PK «J¤Fs‘{Y³ ¦ xl/theme/theme1.xmlíYOoÛ6¿ïSº·²lÉu‚:EìØëÖ¦
So i think it's an encode problem. But i still don't know how can i resolve it.

the issue is your $_SESSION code at the end.
$_SESSION['downloadstatus'] = array(
"status" => "finished",
"message" => "Done"
);
Since the headers have already been output, I'm almost certain you are getting a php warning appended to the end of your excel document. Make the following changes and it should work.
$_SESSION['downloadstatus'] = array(
"status" => "finished",
"message" => "Done"
);
// Send the Excel File to the user
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="template.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;

I find the problem it was so stupid. It's just that it's not allow to put some specials characters in $objPHPExcel->getProperties() so i replace every 'é' by 'e' and now it's work.

Related

Getting Garbled Text while using PHPExcel

I am trying to generate an .ods document using PHP Excel.
Below is the code i am using :
public function init() {
$this->objPHPExcel = new PHPExcel();
}
public function indexAction(){
$iexpertsMapper = new Application_Model_IExpertsMapper();
$response = $iexpertsMapper->getAllIExpertsPaymentDues();
$this->objPHPExcel->getProperties()->setCreator("D")
->setLastModifiedBy("D")
->setTitle("D")
->setSubject("D")
->setDescription("D")
->setKeywords("D")
->setCategory("D");
// Headers
$this->objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'H')
->setCellValue('B1', strtotime("today"))
->setCellValue('C1', 'CTPL');
// Redirect output to a client’s web browser (OpenDocument)
header('Content-Type: application/vnd.oasis.opendocument.spreadsheet');
header('Content-Disposition: attachment;filename=bank.ods');
$objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'OpenDocument');
ob_end_clean();
$objWriter->save('php://output');
exit;
}
Whenever i hit the code from the browser, an ods document is downloaded with gibberish text. I tried various things including adding ob_end_clean(); in my code. But nothing seems to work. Following text appears in my ODS document : �QĿi!��K�y3�J<���Z1�0?Y�L%zV.
This is what i see when i open the document :

PHPExcel file is not downloading

I'm attempting to download a spreadsheet using PHPExcel but so far nothing but a blank page.
$items = array("test 1", "test 2", "test 3");
/** PHPExcel */
require_once dirname(__FILE__) . '/../../Classes/PHPExcel.php';
// Create new PHPExcel object
//echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("User 1");
$objPHPExcel->getProperties()->setLastModifiedBy("User 1");
$objPHPExcel->getProperties()->setTitle(" Quotes");
$objPHPExcel->getProperties()->setSubject("Quotes");
$objPHPExcel->getProperties()->setDescription("Quotes");
// Add some data
$objPHPExcel->setActiveSheetIndex(0);
$loop = 0;
foreach($items as $value) {
$objPHPExcel->getActiveSheet()->SetCellValue('No', $loop);
$objPHPExcel->getActiveSheet()->SetCellValue('Item Name', $value);
$loop++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="quotes.xls"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
I've enabled errors and still blank page.
How do i solve? No file is downloading?
Well you should should be getting errors, or something written to your logs, because your code will throw a fatal
Fatal error: Uncaught exception 'PHPExcel_Exception' with message 'Invalid cell coordinate NO' in ...
Because NO is not a valid cell address in an Excel worksheet, nor is Item Name
The problem is these lines:
$objPHPExcel->getActiveSheet()->SetCellValue('No', $loop);
$objPHPExcel->getActiveSheet()->SetCellValue('Item Name', $value);
A valid cell address is a column (like A) combined with a row (like 1) to give a cell address of A1
Perhaps you meant something like:
$objPHPExcel->getActiveSheet()->SetCellValue('A'.($loop+1), 'No');
$objPHPExcel->getActiveSheet()->SetCellValue('B'.($loop+1), 'Item Name');
$objPHPExcel->getActiveSheet()->SetCellValue('C'.($loop+1), $loop);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.($loop+1), $value);

Exporting data to excel (multiple sheets) using php

I am trying to export data to Excel using this PHP Class, so far things are working fine and the export is being generated. But now I have a new requirement of generating multiple sheets inside a single excel file.
For example if i have two arrays, i want both to be on separate sheets.
$myarray1 = array (
1 => array ("Oliver", "Peter", "Paul"),
array ("Marlene", "Mica", "Lina")
);
$myarray2 = array (
1 => array ("Oliver", "Peter", "Paul"),
array ("Marlene", "Mica", "Lina")
);
At present both arrays are being exported on a single sheet
$xls = new Excel_XML;
$xls->addArray ( $myarray );
$xls->addArray ( $myarray2 );
$xls->generateXML ( "testfile" );
I am wondering if someone tried this before and was able to achieve it and I will appreciate any help I can get on this.
i would suggest you to use PHPExcel library.supports variety of formats, can do visual formatting and is easy to use.
You can find more about it at their webpage: http://phpexcel.codeplex.com/
You can do a lot more of course, reading excel files, setting visual styles, creating plots, expressions and lot more.
you can even use fgetcsv http://php.net/manual/en/function.fgetcsv.php
this example using PHPExcel
function exportToExcelsheets($data, $fileName){
/* Create new PHPExcel object*/
$objPHPExcel = new PHPExcel();
$sheet_index = 0;
foreach ($data as $s=>$sheet){
/* Create a first sheet, representing sales data*/
$alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','V','W','X','Y','Z'];
$objPHPExcel->setActiveSheetIndex($sheet_index);
$head_keys = array_keys($sheet[0]);
foreach ($head_keys as $a=>$headval){
$objPHPExcel->getActiveSheet()->setCellValue($alpha[$a].'1', $headval);
}
$i=2;
foreach($sheet as $row) {
$index = 0;
foreach ($row as $v=>$value){
$value = isset($value)?$value:'';
$objPHPExcel->getActiveSheet()->setCellValue($alpha[$index].$i,$value);
$index++;
}
$i++;
}
/*Rename sheet*/
$objPHPExcel->getActiveSheet()->setTitle('sheet_'.$s);
/* Create a new worksheet, after the default sheet*/
$objPHPExcel->createSheet();
$sheet_index++;
}
/* Redirect output to a client’s web browser (Excel5)*/
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=\"$fileName\"");
header('Cache-Control: max-age=0');
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//$objWriter->save('php://output');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}

PHPExcel can't generate data from database

When i open the Excel file message appear:
the file you are trying to open, 'filename".xls', is in a different format than specified by the file extension. verify that the fileis not corrupted and is from a trusted source before opening the file."
The output is like this:
ÐÏࡱá;þÿ þÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
>¶#d‹‹dggÿÿÿÿÿ .....
Here is my code..
<?php
require_once 'database.php';
include 'PHPExcel.php';
$phpExcel = new PHPExcel();
$phpExcel->getActiveSheet()->setTitle("My Sheet");
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Name.')
->setCellValue('B1', 'Age');
$qry_table = ("SELECT * FROM MEMBERS");
$inc=2;
while($data_array = mysql_fetch_array($qry_table))
{
$name = $data_array['Name'];
$age = $data_array['Age'];
$$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name)
->setCellValue('B'.$inc, $age);
$inc++;
}
$phpExcel->setActiveSheetIndex(0);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
$objWriter->save("php://output");
exit;
Where's your "mysql_query()" to query the database?
Change
$qry_table = ("SELECT * FROM MEMBERS");
to
$qry_table = mysql_query("SELECT * FROM MEMBERS");
//Edit:
And you've got a pointer ref. to an a variable which does not exsits
Change:
$$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name)
->setCellValue('B'.$inc, $age);
to:
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A'.$inc, $name);
$phpExcel->setActiveSheetIndex(0)
->setCellValue('B'.$inc, $age);
When you get this error, we always recommend opening the file in a text editor and checking for leading or trailing white spaces (spaces, tabs, newlines), or a BOM marker, or any obvious PHP error messages in plain text in the file.
Try saving the file to your webserver, then opening it and see if the same error occurs

PHPExcel generating totally jacked up output

Greetings,
I am having trouble figuring out how to properly use PHP in general and PHPExcel in particular. I have read multiple posts on this topic and yet I've been running around in circles. Here is the relevant portion of my jacked up code:
$viewinv = mysql_connect($sqlsrv,$username,$password);
if (!$viewinv) { die('Could not connect to SQL server. Contact administrator.'); }
mysql_select_db($database, $viewinv) or die('Could not connect to database. Contact administrator.');
$query = "select unit_id,config,location from inventory;";
$result = mysql_query($query);
if ($result = mysql_query($query) or die(mysql_error())) {
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('blah');
$rowNumber = 1;
$headings = array('Unit ID','Config','Location');
$objPHPExcel->getActiveSheet()->fromArray(array($headings),NULL,'A'.$rowNumber);
$rowNumber++;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myFile.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
echo 'a problem has occurred... no data retrieved from the database';
PHPExcel is definitely outputting data from the query, I can see bits and pieces of plaintext, but it is surrounded by a ton of random characters as if though I am looking at the contents of a compressed or compiled piece of data.
For example:
PKâh¿>G’D²Xð[Content_Types].xml­”MNÃ0…÷œ"ò%nY „švAa •(0ö¤±êØ–gúw{&i‰#ÕnbEö{ßøyìÑdÛ¸l mð¥‘×ÁX¿(ÅÛü)¿’òF¹à¡;#1_滘±Øc)j¢x/%ê…Eˆày¦
Any pointers would be extremely appreciated
Your problem is certainly in outputting more content than just Excel data (which is contained in output buffer).
To solve your problem, just call
ob_clean(); //this will clean the output buffer
before sending header.
The problem will likely be resolved by matching the correct writer types to the correct content-types and file extension.
XLSX (office 2007+):
Writer : Excel2007 (PHPExcel_Writer_Excel2007)
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
XLS (before office 2007):
Writer : Excel5 (PHPExcel_Writer_Excel5)
Content-Type: application/vnd.ms-excel

Categories