While exporting to XLS output is garbage even with correct headertypes - phpexcel

I have tried some solutions provided in other questions about exporting to Excel sheet using PHP,still not working.Also I referred to PHPExcel library examples still stuck.
Here's my code.
<?php
ob_start();
require_once 'Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties() ->setCreator("MeritTrac")
->setTitle("PHPExcel Test document")
->setSubject("PHPExcel Subject")
->setDescription("This is generatred by PHPExcel");
$objPHPExcel ->setActiveSheetIndex(0)
->setCellValue('A1','Hello')
->setCellValue('B1','Test')
->setCellValue('C1','Color')
->setCellValue('D1','World');
$objPHPExcel ->setActiveSheetIndex(0)
->setCellValue('A4','Miscellaneous Glyph')
->setCellValue('A5','ífá');
$objPHPExcel ->setActiveSheetIndex(0);
header('Content type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//header('Content type:application/vnd.ms-excel');
header('Content disposition: csv;filename="download.xlsx"');
header('Cache-Control: max-age=0');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public');
echo "Test print";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
<?php
ob_end_flush();
?>
Output:
http://imgur.com/a/5AsWF
Please find what I am missing coz this code gives me garbage output.

Related

Don't print the chart in pdf with phpexcel

Currently I'm making my reports with phpexcel, everythink is ok when I make the report with charts in xlsx;
... $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007'); $objWriter->setIncludeCharts(TRUE);
$objWriter->save('php://output');
exit;
and when I do it in html with;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->setIncludeCharts(TRUE);
$objWriter->save('php://output');
But the problem is when I want to create the pdf file my response is a pdf without charts, and yes previously I added the PHPExcel_Settings::PDF_RENDERER_MPDF AND PHPExcel_Settings::CHART_RENDERER_JPGRAPH;
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->setIncludeCharts(TRUE);
$objWriter->save('php://output');
May be there is a problem because I save the file in the client browser?

read and write of excel in phpexcel

i accomplished the read of excel with php but the write i cannot, i not know why..
in the file to read, take one column and write in a new file excel and paste there is.. for now only that..
Thank to all..
<?php
require_once "excel/Classes/PHPExcel.php";
require_once "excel/Classes/PHPExcel/IOFactory.php";
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
set_time_limit ( 0 );
ini_set('memory_limit', '-1');
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
?>
<form action="" method="post" enctype="multipart/form-data">
Desea comenzar el proceso ?
<input type="submit" value="Aceptar" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$objPHPExcel_load = new PHPExcel();
$PHPExcel_save = new PHPExcel();
$PHPExcel_save->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$PHPExcel_save->setActiveSheetIndex(0)
->setCellValue('A1', 'Cedula');
$PHPExcel_save->getActiveSheet()->setTitle('Simple');
$PHPExcel_save->setActiveSheetIndex(0);
$inputFileName = 'discussdesk.xlsx';
$objPHPExcel_load = PHPExcel_IOFactory::load($inputFileName);
$objWorksheet = $objPHPExcel_load->getActiveSheet();
$cantidad = $objWorksheet->getHighestRow();// tamaño de los registros
$objeto_pegar = $PHPExcel_save->getActiveSheet(0);
echo "cantidad : ".$cantidad;
$prueba = true;
$row = 2;
$column = 1;
for($i = 1;$i <= $cantidad;$i++){
$celda = trim($objWorksheet->getCellByColumnAndRow(7, $row)->getValue());
$PHPExcel_save->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1, $row, $celda);
echo $celda.'<br>';
if(is_null($celda)){
break;
}
$row +=1;
}
$PHPExcel_save->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel_save, 'Excel2007');
$objWriter->save('php://output');
}
?>
$PHPExcel_writer = new PHPExcel();
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); // crea el archivo a leer
$PHPExcel_ = $objReader->load('testFile.xlsx'); // load the file
$PHPExcel_->setActiveSheetIndex(0)
->setCellValue('A1', 'field1')
->setCellValue('B1', 'field2')
->setCellValue('C1', 'field3')
->setCellValue('D1', 'field4')
->setCellValue('E1', 'field5')
->setCellValue('F1', 'field6'); // write the first row(tittle)
//$PHPExcel_writer->setActiveSheet()->setTitle('Simple');
$PHPExcel_->setActiveSheetIndex(0);
//
$objPHPExcel_load = new PHPExcel();
$inputFileName = 'discussdesk.xlsx';
$objPHPExcel_load = PHPExcel_IOFactory::load($inputFileName);
$objWorksheet = $objPHPExcel_load->getActiveSheet();
$cantidad = $objWorksheet->getHighestRow();// size of row*/
//echo "count : ".$cantidad;
//$row = 2;
//$column = 1;
//$PHPExcel_writer->getActiveSheet()->setTitle('Simple');
//$PHPExcel_writer->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1, 1, "prueba");
for($i = 1;$i <= 1000;$i++){ ?>
<script> envia_barra(<? echo $i; ?>);
</script>
<?php
/*$celda = trim($objWorksheet->getCellByColumnAndRow(12, $row+3)->getValue());
$data = file_get_contents("youweb?param=".$celda);
set_time_limit(5);
$PHPExcel_->getActiveSheetIndex(0);
if(preg_match('|<td width="180" class="tblbgcolort"><strong>Departamento:</strong></td>\s+<td width="400" class="tblbgcolort">(.*?)</td>|is' , $data , $dep )){
preg_match('|<td width="180" class="tblbgcolort"><strong>Departamento:</strong></td>\s+<td width="400" class="tblbgcolort">(.*?)</td>|is' , $data , $dep );
preg_match('|<td class="tblbgcolor"><strong>Municipio:</strong></td>\s+<td class="tblbgcolor">(.*?)</td>|is' , $data , $mun );
preg_match('%<strong>Puesto:</strong>.+?<td>(.+?)</td>%si',$data,$puesto);
preg_match("%<div style='float:left;'>(.*?)<\/div>%si", $data , $dir );
preg_match('|<td class="tblbgcolor"><strong>Mesa</strong></td>\s+<td class="tblbgcolor">(.*?)</td>|is' , $data , $mes );
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(0,$row, $celda);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1,$row,$dep[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(2,$row,$mun[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(3,$row,$puesto[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(4,$row,$dir[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(5,$row,$mes[1]);
}else{
$PHPExcel_->getActiveSheet()->setCellValueByColumnAndRow(0,$row,$celda);
$PHPExcel_->getActiveSheet()->setCellValueByColumnAndRow(1,$row ,"No hay registro");
}
$row++;
if(is_null($celda)){
break;
}
}
//$PHPExcel_writer->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel_, 'Excel2007');
$objWriter->save('testFile.xlsx');
//$objWriter->save('php://output');
//header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//header("Content-Disposition: attachment;filename=\"discussdesk.xlsx\"");
//header("Cache-Control: max-age=0");
//$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel_writer, 'Excel2007');
//$objWriter->save('php://output');
exit;

PHPExcel File format or extension is not valid

I'm using phpexcel for export my query in excel file; however after I created file(which is xslx format), I can not open my file in excel. It gives "the file format or extension is not valid. Verify that the file has not been corrupted and that the file extension matches the file format of the file" error. When I open the file in texteditor(mine is npp) I see my php file's css codes and some part of my html codes. My code is like that;
if( ! empty($_POST['export'])){
$query = "SELECT * FROM asd ORDER BY asdf LIMIT 10";
$headings = array('Timestamp', 'h1','h2');
require 'Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('List of Users');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
$rowNumber = 2;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
$objPHPExcel->getActiveSheet()->freezePane('A2');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="userList.xlsx"');
header("Content-Transfer-Encoding: binary ");
//ob_end_clean();
//header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
I'm stucked please help. Thank you.
As described in the manual.... if anything else is being output to the browser, this will corrupt the output file.
Open the file in a text editor, and look for leading or trailing whitespace characters (spaces, tabs, newlines) or a BOM marker at the beginning of the output, or for any obvious PHP plaintext error messages in the content. These are the most obvious causes of this problem. Once you've identified the spurious characters, check through your script to see where that output is being generated, and remove it.
In your case, that means don't output your css and html.
EDIT
xlsx is the extension for an OfficeOpenXML Excel2007 file, not for a BIFF 8 xls file.... be consistent in your headers (mime type and file extension) and Writer
Either:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="userList.xls"');
or
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="userList.xlsx"');
Following documentation or comments somewhere I read, I had this:
$objWriter = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
// etc
instead of
$objWriter = PHPExcel_IOFactory::createWriter($spreadsheet, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// etc
And that caused Firefox and IE/Edge to append an .xls to the filename and also give the error message when trying to open the file directly instead of downloading it. When downloading the file and opening the spreadsheet though, everything was fine.

PHPExcel output file is empty

I downloaded PHPExcel library but could not use it. I am using one of the examples in the Library but it downloads an empty excel file. Here is my code.
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("document");
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'world!');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
header("Content-Type: application/vnd.ms-excel");
header('Content-Disposition: attachment;filename="deneme.xls"');
Am i forgetting something here? It is simple but downloaded excel file is empty. Does anyone have an idea?
EDIT:
Solved: I have to add these lines:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Add this:
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
die();
You're forgetting to instantiate a writer and then save

drupal 6 can we write a php file in drupal which changes the headers

i have written a small code which creates a word document but
i got the following errors
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
$fp = fopen("test.doc", 'w+');
$str = "<B>This is the text for the word file created through php programming</B><br>test to create a doc file from php";
ob_start();
include('index.php');
$result = ob_get_clean();
fwrite($fp, $result);
echo "executed";
header("Content-Disposition: attachment; filename=test.doc");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize("test.doc"));
header("Connection: close");
fclose($fp);
?>
warning: Cannot modify header information - headers already comnt by (output started at /var/www/www.example.com/htdocs/test_createdoc.php:6) in /var/www/www.example.com/htdocs/test_createdoc.php on line 19.
warning: Cannot modify header information - headers already comnt by (output started at /var/www/www.example.com/htdocs/test_createdoc.php:6) in /var/www/www.example.com/htdocs/test_createdoc.php on line 20.
warning: Cannot modify header information - headers already comnt by (output started at /var/www/www.example.com/htdocs/test_createdoc.php:6) in /var/www/www.example.com/htdocs/test_createdoc.php on line 21.
warning: Cannot modify header information - headers already comnt by (output started at /var/www/www.example.com/htdocs/test_createdoc.php:6) in /var/www/www.example.com/htdocs/test_createdoc.php on line 22
i have even remove the white spaces between php tags
It looks like echo "executed"; sends output before the headers. PHP then stops the headers from sending, because HTTP requires headers to come before output. If removing that doesn't fix it, try commenting out include('index.php'); to test if the output is coming from there.

Resources