Add custom title to excel columns using PHPEXCEL - php

i am writing values from a while loop into an excel sheet using PHPEXCEL. in doing this i need to write a title for each of the rows . what i only get now is the result from the database , how can i add a custom title
e.g
Premier League
EVENTID STARTDATE STATUS
1022 17-09-2013 Won
Premier League
EVENTID STARTDATE STATUS
3421 22-10-2012 lost
Here is my code
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test2");
$sql=mysql_query("select * from event");
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
while($row = mysql_fetch_array($sql)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['EventID']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['StartDate']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['Status']);
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
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($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;

something like this:
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$customTitle = array ('test a','test b','test c');
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $customTitle[0]);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $customTitle[1]);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $customTitle[2]);
$rowCount++;
while($row = mysql_fetch_array($sql)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['EventID']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['StartDate']);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $row['Status']);
$rowCount++;
}

Related

PHPExcel writer returns empty file

Im currently writing a data export using PHPExcel and keep getting an empty file.
I've made a test script that should give me an excel file with 3 test cells filled but it also gives me an empty excel file.
When i print_r the $objphpexcel it still shows that the cells are filled.
But when i print_r the writer, it only has the header data available and no cell content..
<?php
include_once 'models/PHPExcel.php';
include_once 'models/PHPExcel/IOFactory.php';
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator('Company')
->setLastModifiedBy('User')
->setTitle('Sample_title');
// Add header (first row) data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'EXCEL EXPORT')
->setCellValue('B1', 'TEST')
->setCellValue('C1', 'CEL');
$next_excelrow=2;
//ITERATION TROUGH DATA HERE
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('A');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
//echo'<pre>'.print_r($objPHPExcel,true).'</pre>';exit; <-- this print_r still has the data
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="sample_export.xls"');
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
//header('Content-Type: text/html; charset=UTF-8');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
As you can see I've already narrowed it down to a simple export and still an empty corrupt file is what i get served as a download..
Can anyone help?
Thanks!
try to change $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
to $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="file.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('file.xlsx');
try to save it to file like example, not to php://output. Works for me.
Since PHPExcel is deprecated I'm moving to PHPSpreadsheet

php excel download a file

DevelopersI am using Yii1 and I want to generate a report using PHPExcel extension but my file is not ready to download, instead it appears in console. I also set headers but still file is not ready for download. I can't find exact answer. please resolve my problem
public function GenerateReport($dataProvider)
{
$phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');
include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
$objPHPExcel = new PHPExcel();
$fileName = 'report-'.uniqid().'.xlsx';
$objPHPExcel->getProperties()->setCreator("Palash Gupta");
$objPHPExcel->getProperties()->setTitle($fileName);
$objPHPExcel->getProperties()->setSubject("Placement Student List");
$objPHPExcel->getProperties()->setDescription("Placement Student List");
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Name');
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Course');
$rowCount = 2;
foreach ($dataProvider->getData() as $data)
{
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $data['sd_fname']);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $data['fk_mc_id']);
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
Try this:
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $fileName .'"');
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($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
Ref: https://github.com/PHPOffice/PHPExcel/blob/1.8/Examples/01simple-download-xls.php

PHPExcel download excel file

have a problem to download excel file. When im saving on server its worked ok. But when i try to download things goes wrong
enter code hererequire_once('Classes/PHPExcel.php');
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( ' memoryCacheSize ' => '1024MB');
ini_set("memory_limit","-1");
ini_set('max_execution_time', 13600);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Techizer")
->setLastModifiedBy("Techizer")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setCategory("Test result file");
if($file=="employer")
{
// Rename worksheet
$file = 'employer';
$objPHPExcel->getActiveSheet()->setTitle($file);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1','Employer Name')
->setCellValue('B1','Emp ID')
->setCellValue('C1','Designation')
->setCellValue('D1','Zone')
->setCellValue('E1','Password');
$query = $this->session->userdata('employ');
$query = preg_replace('/LIMIT.*/', '', $query);
$res = $this->common_model->execute_query($query);
$row = 2;
foreach($res as $result)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$row,$result->profile_name)
->setCellValue('B'.$row,$result->profile_empid)
->setCellValue('C'.$row,$result->profile_desig)
->setCellValue('D'.$row,$result->profile_zone)
->setCellValue('E'.$row,$result->profile_pass);
$row++;
}
header('Content-Disposition: attachment;filename=Employer list'.date("Y-m-d").'.xls');
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
//header('Content-Disposition: attachment;filename=report.xls');
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($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
it gives an excel file with this content:
PK–jGG’D²Xð[Content_Types].xml­”MNÃ0…÷œ"ò%nY

Retrieve table in database to phpexcel

I am using php excel export the data in database to Excel format.
I can retrieve all the data from database to Excel ady. But if i wanna to retrieve the column name of the table, how i going to do. Anyone can help?
Here's my code:
<?php
header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=product.xls");
header("Pragma:no-cache");
header("Expires:0");
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header('Content-Disposition: attachment; filename="export.csv"');
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/Writer/Excel2007.php';
require_once '../Classes/PHPExcel/IOFactory.php';
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("litako", $con);
$objPHPExcel = new PHPExcel();
$res= mysql_query("SELECT * FROM vendorlist ");
/** Error reporting */
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$objPHPExcel = new PHPExcel();
if(!$res){
die("Error");
}
$col = 0;
$row = 3;
while($mrow = mysql_fetch_assoc($res)) {
$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);
// Save Excel 2007 file
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
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($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
You already have the column name in your while loop where you call mysql_fetch_assoc. The $key value is the column name. So here is an updated portion of your code:
while($mrow = mysql_fetch_assoc($res)) {
$col = 0;
foreach($mrow as $key=>$value) {
// TODO: Do Something With the Column Name like set the row header. Note this crude code sets it every time. You really just want to do it the first time only.
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 0, $key);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row + 1, $value);
$col++;
}
$row++;
}

how to download excel file in internet explorer browser with phpexcel library

i have written code that is working in Mozilla firefox but not working in internet explorer
i cannot solve it. in internet explorer its complete page loding with out popup download .
i need to generete excel file with IE support also.please help me.
here is my code.
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(18);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Agent Code')
->setCellValue('B1', 'Month');
$i=2;
while($row1=mysql_fetch_array($rs))
{
$month = $row1['smonth']+1;
$month_name = date( 'F', mktime(0, 0, 0, $month) );
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i, $row1['scode'])
->setCellValue('B'.$i, $month_name)
->setCellValue('C'.$i, $row1['syear']);
$i++;
}
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
This is complete solution
use
header('Pragma: ');
Your issue is relate with headers were missing.
Try to replace your header code with this following code:
setcookie("fileLoading","true");
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$viNameFile.'.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($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

Categories