PHPExcel Get data fromDatabase and put value into cells - phpexcel

Need some help...
So, i'm trying to export data from database to excel file.
I'm able to fetch data to database,but when i'm exporting it to excel inside the while loop I only got one record.
Please help.I'm using PHPExcel 1.8.0 libray
Here is my code:
<?php
include('config/config_msdb.php');
/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Manila');
// include PHPExcel
require('lib/PHPExcel.php');
// create new PHPExcel object
$objPHPExcel = new PHPExcel;
// set default font
$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
/**
* Define currency and number format.
*/
// currency format, € with < 0 being in red color
$currencyFormat = '#,#0.## \€;[Red]-#,#0.## \€';
// number format, with thousands separator and two decimal points.
$numberFormat = '#,#0.##;[Red]-#,#0.##';
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('YellowCab');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A2:P2')->getFont()->setBold(true)->setSize(12);
// write header
$objSheet->getCell('A2')->setValue('Date');
$objSheet->getCell('B2')->setValue('TC Within 30 mins');
$objSheet->getCell('C2')->setValue('Total TC');
$objSheet->getCell('D2')->setValue('%');
$objSheet->getCell('E2')->setValue("Within 15 mins");
$objSheet->getCell('F2')->setValue("Total TC");
$objSheet->getCell('G2')->setValue("%");
$objSheet->getCell('H2')->setValue("Excellent TC");
$objSheet->getCell('I2')->setValue("Total TC");
$objSheet->getCell('J2')->setValue("%");
$objSheet->getCell('K2')->setValue('Good TC');
$objSheet->getCell('L2')->setValue('Total TC');
$objSheet->getCell('M2')->setValue('%');
$objSheet->getCell('N2')->setValue('Poor TC');
$objSheet->getCell('O2')->setValue('Total TC');
$objSheet->getCell('P2')->setValue('%');
//get record
$query="SELECT pr.TransDate,pr.TC30,pr.Total_TRX1,cast(round(pr.Hitrate,0) as nvarchar (10))+'%' AS Hitrate ,pr.PDT15,pr.Total_TRX2,cast(round(pr.ProdTime,0) as nvarchar(10))+'%' AS ProdTime,pr.Excellence,pr.Total_TRX4,
cast(round(pr.ExcelPercent,0) as nvarchar(10))+'' AS ExcelPercent,pr.Good,pr.Total_TRX5,cast(round(pr.GoodPercent,0) as nvarchar(10))+'%' AS GoodPercent,
pr.Poor,pr.Total_TRX6,cast(round(pr.PoorPercent,0) as nvarchar(10))+'%' AS PoorPercent,lp.area_name FROM part_view AS pr
LEFT JOIN lp_areas AS lp ON lp.id = pr.StoreID
WHERE lp.is_delete=0 AND lp.area_status=1 AND lp.id!='43' ORDER BY pr.TransDate DESC";
$que = mssql_query($query);
$i = '3';
while($row=mssql_fetch_array($que)){
$transdate=date('Y-m-d',strtotime($row["TransDate"]));
$tc30=$row["TC30"];
$totaltrx1=$row["Total_TRX1"];
$hitrate=$row["Hitrate"];
$pdt15=$row["PDT15"];
$totaltrx2=$row["Total_TRX2"];
$prodtime=$row["ProdTime"];
$excellence=$row["Excellence"];
$totaltrx4=$row["Total_TRX4"];
$excelpercent=$row["ExcelPercent"];
$good=$row["Good"];
$totaltrx5=$row["Total_TRX5"];
$goodpercent=$row["GoodPercent"];
$poor=$row["Poor"];
$totaltrx6=$row["Total_TRX6"];
$poorpercent=$row["PoorPercent"];
$storename=$row["area_name"];
// we could get this data from database, but here we are writing for simplicity
$objSheet->getCell('A'.$i.'')->setValue($transdate);
$objSheet->getCell('B'.$i.'')->setValue($tc30);
$objSheet->getCell('C'.$i.'')->setValue($totaltrx1);
$objSheet->getCell('D'.$i.'')->setValue($hitrate);
$objSheet->getCell('E'.$i.'')->setValue($pdt15);
$objSheet->getCell('F'.$i.'')->setValue($totaltrx2);
$objSheet->getCell('G'.$i.'')->setValue($prodtime);
$objSheet->getCell('H'.$i.'')->setValue($excellence);
$objSheet->getCell('I'.$i.'')->setValue($totaltrx4);
$objSheet->getCell('J'.$i.'')->setValue($excelpercent);
$objSheet->getCell('K'.$i.'')->setValue($good);
$objSheet->getCell('L'.$i.'')->setValue($totaltrx5);
$objSheet->getCell('M'.$i.'')->setValue($goodpercent);
$objSheet->getCell('N'.$i.'')->setValue($poor);
$objSheet->getCell('O'.$i.'')->setValue($totaltrx6);
$objSheet->getCell('P'.$i.'')->setValue($poorpercent);
$i++;
// autosize the columns
$objSheet->getColumnDimension('A')->setAutoSize(true);
$objSheet->getColumnDimension('B')->setAutoSize(true);
$objSheet->getColumnDimension('C')->setAutoSize(true);
$objSheet->getColumnDimension('D')->setAutoSize(true);
$objSheet->getColumnDimension('E')->setAutoSize(true);
$objSheet->getColumnDimension('F')->setAutoSize(true);
$objSheet->getColumnDimension('G')->setAutoSize(true);
$objSheet->getColumnDimension('H')->setAutoSize(true);
$objSheet->getColumnDimension('I')->setAutoSize(true);
$objSheet->getColumnDimension('J')->setAutoSize(true);
$objSheet->getColumnDimension('K')->setAutoSize(true);
$objSheet->getColumnDimension('L')->setAutoSize(true);
$objSheet->getColumnDimension('M')->setAutoSize(true);
$objSheet->getColumnDimension('N')->setAutoSize(true);
$objSheet->getColumnDimension('O')->setAutoSize(true);
$objSheet->getColumnDimension('P')->setAutoSize(true);
//Setting the header type
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="file.xlsx"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
/* If you want to save the file on the server instead of downloading, replace the last 4 lines by
$objWriter->save('test.xlsx');
*/
}//end get rows
?>
Thanks in advance

Just to update I have successfully exported all data fetched from my database.
So here is my solution:
$i = '3';
while($row=mssql_fetch_array($que)){
$transdate=date('Y-m-d',strtotime($row["TransDate"]));
$tc30=$row["TC30"];
$totaltrx1=$row["Total_TRX1"];
$hitrate=$row["Hitrate"];
$pdt15=$row["PDT15"];
$totaltrx2=$row["Total_TRX2"];
$prodtime=$row["ProdTime"];
$excellence=$row["Excellence"];
$totaltrx4=$row["Total_TRX4"];
$excelpercent=$row["ExcelPercent"];
$good=$row["Good"];
$totaltrx5=$row["Total_TRX5"];
$goodpercent=$row["GoodPercent"];
$poor=$row["Poor"];
$totaltrx6=$row["Total_TRX6"];
$poorpercent=$row["PoorPercent"];
$storename=$row["area_name"];
$data[] = array(
'TransDate'=>$transdate,
'TC30'=>$tc30,
'Total_TRX1'=>$totaltrx1,
'Hitrate'=>$hitrate,
'PDT15'=>$pdt15,
'Total_TRX2'=>$totaltrx2,
'ProdTime'=>$prodtime,
'Excellent'=>$excellent,
'Total_TRX4'=>$totaltrx4,
'ExcelPercent'=>$excelpercent,
'Good'=>$good,
'Total_TRX5'=>$totaltrx5,
'GoodPercent'=>$goodpercent,
'Poor'=>$poor,
'Total_TRX6'=>$totaltrx6,
'PoorPercent'=>$poorpercent
);
}
$array = stripslashes(json_encode($data));
$json = (object)json_decode($array);
foreach($json AS $datas){
$objSheet->getCell('A'.$i.'')->setValue($datas->TransDate);
$objSheet->getCell('B'.$i.'')->setValue($datas->TC30);
$objSheet->getCell('C'.$i.'')->setValue($datas->Total_TRX1);
$objSheet->getCell('D'.$i.'')->setValue($datas->Hitrate);
$objSheet->getCell('E'.$i.'')->setValue($datas->PDT15);
$objSheet->getCell('F'.$i.'')->setValue($datas->Total_TRX2);
$objSheet->getCell('G'.$i.'')->setValue($datas->ProdTime);
$objSheet->getCell('H'.$i.'')->setValue($datas->Excellence);
$objSheet->getCell('I'.$i.'')->setValue($datas->Total_TRX4);
$objSheet->getCell('J'.$i.'')->setValue($datas->ExcelPercent);
$objSheet->getCell('K'.$i.'')->setValue($datas->Good);
$objSheet->getCell('L'.$i.'')->setValue($datas->Total_TRX5);
$objSheet->getCell('M'.$i.'')->setValue($datas->GoodPercent);
$objSheet->getCell('N'.$i.'')->setValue($datas->Poor);
$objSheet->getCell('O'.$i.'')->setValue($datas->Total_TRX6);
$objSheet->getCell('P'.$i.'')->setValue($datas->PoorPercent);
$i++;
}
Thanks!

Related

Creating spreadsheet with PHPExcel

I am trying to write to a .xls file with PHP. I have tried many examples of code picked up from various sites, but get the same error each time:
Fatal error: Cannot redeclare class PHPExcel in .... line 44
This suggests that I have included PHPExcel more than once, but this is not the case. Can anyone give me a pointed to what I am doing wrong?
Thanks in advance.
Here is my code:
<?php
// include PHPExcel
require_once 'PHPExcel.php';
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// create new PHPExcel object
$objPHPExcel = new PHPExcel;
// set default font
$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objPHPExcel->getDefaultStyle()->getFont()->setSize(8);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
/** * Define currency and number format. */
// currency format, € with < 0 being in red color
$currencyFormat = '#,#0.## \€;[Red]-#,#0.## \€';
// number format, with thousands separator and two decimal points.
$numberFormat = '#,#0.##;[Red]-#,#0.##';
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('My sales report');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:D1')->getFont()->setBold(true)->setSize(12);
// write header
$objSheet->getCell('A1')->setValue('Product');
$objSheet->getCell('B1')->setValue('Quanity');
$objSheet->getCell('C1')->setValue('Price');
$objSheet->getCell('D1')->setValue('Total Price');
// we could get this data from database, but for simplicty, let's just write it
$objSheet->getCell('A2')->setValue('Motherboard');
$objSheet->getCell('B2')->setValue(10);
$objSheet->getCell('C2')->setValue(5);
$objSheet->getCell('D2')->setValue('=B2*C2');
$objSheet->getCell('A3')->setValue('Processor');
$objSheet->getCell('B3')->setValue(6);
$objSheet->getCell('C3')->setValue(3);
$objSheet->getCell('D3')->setValue('=B3*C3');
$objSheet->getCell('A4')->setValue('Memory');
$objSheet->getCell('B4')->setValue(10);
$objSheet->getCell('C4')->setValue(2.5);
$objSheet->getCell('D4')->setValue('=B4*C4');
$objSheet->getCell('A5')->setValue('TOTAL');
$objSheet->getCell('B5')->setValue('=SUM(B2:B4)');
$objSheet->getCell('C5')->setValue('-');
$objSheet->getCell('D5')->setValue('=SUM(D2:D4)');
// bold and resize the font of the last row
$objSheet->getStyle('A5:D5')->getFont()->setBold(true)->setSize(12);
// set number and currency format to columns
$objSheet->getStyle('B2:B5')->getNumberFormat()->setFormatCode($numberFormat);
$objSheet->getStyle('C2:D5')->getNumberFormat()->setFormatCode($currencyFormat);
// create some borders
// first, create the whole grid around the table
$objSheet->getStyle('A1:D5')->getBorders()->
getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
// create medium border around the table
$objSheet->getStyle('A1:D5')->getBorders()->
getOutline()->setBorderStyle(PHPExcel_Style_Border::BORDER_MEDIUM);
// create a double border above total line
$objSheet->getStyle('A5:D5')->getBorders()->
getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_DOUBLE);
// create a medium border on the header line
$objSheet->getStyle('A1:D1')->getBorders()->
getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_MEDIUM);
// autosize the columns
$objSheet->getColumnDimension('A')->setAutoSize(true);
$objSheet->getColumnDimension('B')->setAutoSize(true);
$objSheet->getColumnDimension('C')->setAutoSize(true);
$objSheet->getColumnDimension('D')->setAutoSize(true);
// write the file
$objWriter->save('test.xlsx');
?>

PHPExcel help - How to Export data with PHPexcel in an custom table layout

I am quite new to PHPExcel and learning PHP as I go. I managed to get PHPexcel to export my data from SQL via the code below. Right now its just outputting in basic style, meaning its just serialized the data from SQL and next record would show up in the next row. I added an image of what I would like to accomplish, is this something possible with PHPexcel or am I dreaming.
If anyone could send me a quick example of how to accomplish this it would be greatly appreciated.
Image
http://postimg.org/image/m3n60hn25/
Below is a working sample of a simple serialized export.
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "IMC_COE2";
$dbpass = "XXX";
$dbname = "IMC_COE2";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require '/Excelphp/Classes/PHPExcel.php';
// simple query
$query = 'SELECT client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note FROM tbl_address ORDER by team_name DESC';
$headings = array('Client Name','Team Name','Prime Contact','Comments','Backup Contacts','Comments','Escalation 1','Comments','Escalation 2','Comments','Escalation 3','Comments','Escalation 4','Comments','Additional notes');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('List of Users');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 2;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line won't scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
// Save as an Excel BIFF (xls) file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="userList.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
echo 'a problem has occurred... no data retrieved from the database';
UPDATE October 2nd:
Here is where I am at now, the only problem I have is that PHPExcel's export is only showing 1 record. I cant figureout the missing code that will show me all the records in the same format and cell array.
Image:
http://postimg.org/image/8gicg5gtl/8a918f3e/
Heres my progress so far but still not getting a successful loop:
<?php
/** PHPExcel */
require_once '/Excelphp/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->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");
$objPHPExcel->getActiveSheet()->mergeCells('B2:D2');
$objPHPExcel->getActiveSheet()->mergeCells('B4:D4');
$objPHPExcel->getActiveSheet()->mergeCells('B7:D7');
$objPHPExcel->getActiveSheet()->mergeCells('B12:D12');
$objPHPExcel->getActiveSheet()->mergeCells('C3:D3');
$objPHPExcel->getActiveSheet()->mergeCells('B13:D13');
$objPHPExcel->getActiveSheet()->getStyle('C3:D3')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C5:D5')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C6:D6')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C8:D8')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C9:D9')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C10:D10')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C11:D11')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B13:D13')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
//Setting for borders
$styleArray = array('borders' => array('outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => 'FFA0A0A0'),),),);
$objPHPExcel->getActiveSheet()->getStyle('B2:B13')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('C2:C13')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('D2:D13')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B2:D2')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B3:D3')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B4:D4')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B5:D5')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B6:D6')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B7:D7')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B8:D8')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B9:D9')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B10:D10')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B11:D11')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B12:D12')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B13:D13')->applyFromArray($styleArray);
//Background color on cells
$objPHPExcel->getActiveSheet()->getStyle('B2:D2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B4:D4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B7:D7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B12:D12')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B7:D7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B5')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B8')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B9')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B10')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B11')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', '')
->setCellValue('B1', '')
->setCellValue('C1', '')
->setCellValue('D1', '')
->setCellValue('E1', '')
->setCellValue('A14', '')
->setCellValue('B14', '')
->setCellValue('C14', '')
->setCellValue('D14', '')
->setCellValue('E14', '')
->setCellValue('B3', 'Client:')
->setCellValue('B5', 'Prime:')
->setCellValue('B4', 'Support group contacts')
->setCellValue('B6', 'Backup:')
->setCellValue('B7', 'Escalations')
->setCellValue('B8', 'Escalation 1:')
->setCellValue('B9', 'Escalation 2:')
->setCellValue('B10', 'Escalation 3:')
->setCellValue('B11', 'Escalation 4:')
->setCellValue('B12', 'Notes');
// SQl database connections
$db = mysql_connect("localhost", "IMC_COE2", "IMC123");
mysql_select_db("IMC_COE2",$db);
$sql="select client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER by team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
$row=2;
while($data=mysql_fetch_array($result))
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.$row, $data['client'])
->setCellValue('B'.$row, $data['team_name'])
->setCellValue('C'.($row+3), $data['support_team_prime'])
->setCellValue('D'.($row+3), $data['prime_comments'])
->setCellValue('C'.($row+4), $data['support_team_backup'])
->setCellValue('D'.($row+4), $data['backup_comments'])
->setCellValue('C'.($row+6), $data['escalation1'])
->setCellValue('D'.($row+6), $data['escalation1_comments'])
->setCellValue('C'.($row+7), $data['escalation2'])
->setCellValue('D'.($row+7), $data['escalation2_comments'])
->setCellValue('C'.($row+8), $data['escalation3'])
->setCellValue('D'.($row+8), $data['escalation3_comments'])
->setCellValue('C'.($row+9), $data['escalation4'])
->setCellValue('D'.($row+9), $data['escalation4_comments'])
->setCellValue('B'.($row+10), $data['note']);
}
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Directory Tool Full dump');
// 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)
ob_end_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Export-Directory Tool.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;
?>
Here is the final result, still needs tweaking but big thanks to Mark Baker who helped me out. It takes about 1-2 minutes to load the excel file but it works. I gonna figure out how to optimize the code for best performance.
<?php
/** PHPExcel */
require_once '/Excelphp/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->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");
$rows=2;
//This is the hard coded *non dynamic* cell formatting
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScale(85);
// SQl database connections
$db = mysql_connect("localhost", "IMC_COE2", "IMC123");
mysql_select_db("IMC_COE2",$db);
$sql="select client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER by team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
while($data=mysql_fetch_array($result))
{
//This section is the actual data import fromt he SQL database *dont touch*
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.($rows+1), $data['client']) //this will give cell C2.
->setCellValue('B'.$rows, $data['team_name']) // this will give cell B2
->setCellValue('C'.($rows+3), $data['support_team_prime']) //this will give C5
->setCellValue('D'.($rows+3), $data['prime_comments']) // This will give D5
->setCellValue('C'.($rows+4), $data['support_team_backup']) //This will give C6
->setCellValue('D'.($rows+4), $data['backup_comments']) //This will give D6 etc...
->setCellValue('C'.($rows+6), $data['escalation1'])
->setCellValue('D'.($rows+6), $data['escalation1_comments'])
->setCellValue('C'.($rows+7), $data['escalation2'])
->setCellValue('D'.($rows+7), $data['escalation2_comments'])
->setCellValue('C'.($rows+8), $data['escalation3'])
->setCellValue('D'.($rows+8), $data['escalation3_comments'])
->setCellValue('C'.($rows+9), $data['escalation4'])
->setCellValue('D'.($rows+9), $data['escalation4_comments'])
->setCellValue('B'.($rows+11), $data['note']);
//Row height adjustments
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+3)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+4)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+6)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+7)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+8)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+9)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+11)
->setRowHeight(100);
//Cell Merging
$objPHPExcel->getActiveSheet()->mergeCells('B'.$rows.':D'.$rows);
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+2).':D'.($rows+2));
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+5).':D'.($rows+5));
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+10).':D'.($rows+10));
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rows+1).':D'.($rows+1));
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+11).':D'.($rows+11));
//Cell Wraptext
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+1).':D'.($rows+1))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+3).':D'.($rows+3))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+4).':D'.($rows+4))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+6).':D'.($rows+6))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+7).':D'.($rows+7))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+8).':D'.($rows+8))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+9).':D'.($rows+9))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+11).':D'.($rows+11))->getAlignment()->setWrapText(true);
//Background color on cells
$objPHPExcel->getActiveSheet()->getStyle('B'.$rows.':D'.$rows)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+2).':D'.($rows+2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+5).':D'.($rows+5))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+10).':D'.($rows+10))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+4))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+6))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+7))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+8))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+9))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B'.($rows+1), 'Client:')
->setCellValue('B'.($rows+3), 'Prime:')
->setCellValue('B'.($rows+2), 'Support group contacts')
->setCellValue('B'.($rows+4), 'Backup:')
->setCellValue('B'.($rows+5), 'Escalations')
->setCellValue('B'.($rows+8), 'Escalation 1:')
->setCellValue('B'.($rows+7), 'Escalation 2:')
->setCellValue('B'.($rows+8), 'Escalation 3:')
->setCellValue('B'.($rows+9), 'Escalation 4:')
->setCellValue('B'.($rows+10), 'Notes');
$rows+=14;
}
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Directory Tool Full dump');
// 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)
ob_end_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Export-Directory Tool.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;
?>

create the new sheet in phpexcel and set the cell value

I am trying to use phpexcel to set the template purchase order .
I have set column 25 to 43 is for details of purchase item. It mean it will retrieve data from database and set all the value in column 25 to 43 .As addition ,these column only can fit for 6 item. I am facing problem when the purchase item is too many and cannot fit into the column that i had set.
My code is work,but it is too long. Anyone have a better solution?
after create both sheet,i have to set the other cellvalue one by one in both sheet.It make the code become very long.Appreciate for who can help.
$objPHPExcel->setActiveSheetIndex(0);
$result = mysql_query("SELECT purchasematerial.PONum,purchasematerial.QuoNum,purchasematerial.date, material.product,purchasematerial.description,purchasematerial.unit_price,purchasematerial.UOM,purchasematerial.qua ntity ,purchasematerial.amount FROM purchasematerial INNER JOIN material ON purchasematerial.product=material.id where PONum='$PONum'");
$col=25;
$num=1;
while($row = mysql_fetch_array($result)){
if($col<43){
$objPHPExcel->getActiveSheet()->setCellValue('AA11', $row['PONum']);
$date = new DateTime($row['date']);
$objPHPExcel->getActiveSheet()->setCellValue('AA12', $date->format('d-M-y'));
$objPHPExcel->getActiveSheet()->setCellValue('I45', '=AA12+7');
$QuoNum=$row['QuoNum'];
if ($QuoNum=='' || $QuoNum== null)
$objPHPExcel->getActiveSheet()->setCellValue('I47', "N/A");
else
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum']);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$col, $num);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$col, $row['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$col, $row['description']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$col, $row['unit_price']);
$objPHPExcel->getActiveSheet()->setCellValue('V'.$col, $row['UOM']);
$objPHPExcel->getActiveSheet()->SetCellValue('Y'.$col, $row['quantity']);
$objPHPExcel->getActiveSheet()->SetCellValue('AB'.$col, $row['amount']);
$col=$col+3;
$num++;
}
else{
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);
$col=25;
$objPHPExcel->getActiveSheet()->setCellValue('AA11', $row['PONum']);
$date = new DateTime($row['date']);
$objPHPExcel->getActiveSheet()->setCellValue('AA12', $date->format('d-M-y'));
$objPHPExcel->getActiveSheet()->setCellValue('I45', '=AA12+7');
$QuoNum=$row['QuoNum'];
if ($QuoNum=='' || $QuoNum== null)
$objPHPExcel->getActiveSheet()->setCellValue('I47', "N/A");
else
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum']);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$col, $num);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$col, $row['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$col, $row['description']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$col, $row['unit_price']);
$objPHPExcel->getActiveSheet()->setCellValue('V'.$col, $row['UOM']);
$objPHPExcel->getActiveSheet()->SetCellValue('Y'.$col, $row['quantity']);
$objPHPExcel->getActiveSheet()->SetCellValue('AB'.$col, $row['amount']);
$col=$col+3;
$num++;
}
}
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->getStyle('I45')->getNumberFormat()- >setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15);
$objPHPExcel->getActiveSheet()->setCellValue('AC1', 'WEEKNUM(I45)');
$objPHPExcel->getActiveSheet()->setCellValue('Q44', 'TOTAL');
$objPHPExcel->getActiveSheet()->SetCellValue('Y44','RM');
$objPHPExcel->getActiveSheet()->SetCellValue('AB44', '=SUM(AB25:AB43)');
$objPHPExcel->getActiveSheet()->getStyle('Q44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('Y44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('AA44')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->getStyle('I45')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15);
$objPHPExcel->getActiveSheet()->setCellValue('AC1', 'WEEKNUM(I45)');
$objPHPExcel->getActiveSheet()->setCellValue('Q44', 'TOTAL');
$objPHPExcel->getActiveSheet()->SetCellValue('Y44','RM');
$objPHPExcel->getActiveSheet()->SetCellValue('AB44', '=SUM(AB25:AB43)');
$objPHPExcel->getActiveSheet()->getStyle('Q44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('Y44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('AA44')->getFont()->setBold(true);
One way might be to use the fluent interface.
Instead of
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum']);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$col, $num);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$col, $row['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$col, $row['description']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$col, $row['unit_price']);
$objPHPExcel->getActiveSheet()->setCellValue('V'.$col, $row['UOM']);
$objPHPExcel->getActiveSheet()->SetCellValue('Y'.$col, $row['quantity']);
$objPHPExcel->getActiveSheet()->SetCellValue('AB'.$col, $row['amount']);
do
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum'])
->setCellValue('A'.$col, $num)
->setCellValue('B'.$col, $row['product'])
->SetCellValue('J'.$col, $row['description'])
->SetCellValue('S'.$col, $row['unit_price'])
->setCellValue('V'.$col, $row['UOM'])
->SetCellValue('Y'.$col, $row['quantity'])
->SetCellValue('AB'.$col, $row['amount']);
so that you're not constantly calling $objPHPExcel->getActiveSheet()
For setting the second sheet, as the cells are identical to the first; you could create a function to set the cell values and just call that function twice (basic PHP 101). Alternatively, you could set the cells for the first sheet, then clone that sheet and set the clone as the second sheet.

Delete rows with PHPExcel

I want to delete all rows that start with "//", from Excel sheet, with PHPExcel.
My code:
require '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/IOFactory.php';
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
$path = "del_head.xls";
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for($row=1; $row < $highestRow; ++$row){
$value = $objPHPExcel->getActiveSheet()->getCell('A'.$row)->getValue();
if (substr($value,0,2) == "//") {
$objPHPExcel->getActiveSheet()->removeRow($row, $row);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save($path);
But, the code not delete all rows that start with "//".
I think the problem is with function 'removeRow'.
Thank you very much in advance.
Replace this line
$objPHPExcel->getActiveSheet()->removeRow($row, $row);
with
$objPHPExcel->getActiveSheet()->removeRow($row);
There's one obvious problem with your call to removeRow(): The first argument is the starting row, the second is the number of rows to remove; so if you find a // at row 5, then you're telling PHPExcel to remove 5 rows starting from row 5 (i.e. rows 5 to 9).
You're also reading a file with a .xls extension (assuming that it's a BIFF file from the extension), but saving with the same .xls filename as an OfficeOpenXML file (which is normally a .xlsx file).
So what format actually is your file? What does a call to the IOFactory's identify() method recognise it as? If it's actually a comma- or tab-separated value file (most likely to have a leading //), then you'd be better using PHP's fgetcsv() and fputcsv() functions to process it to remove those lines.
Try this code, Its worked me
$filename = 'path/example.xls';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$row_id = 1; // deleted row id
$number_rows = 2; // number of rows count
if ($objWorksheet != NULL) {
if ($objWorksheet->removeRow($row_id, $number_rows)) {
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
}
}
Please, check the value assigned on line:
$highestRow = $objWorksheet->getHighestRow();
I've tested this code and the value is always 1

PHPexcel - How can I load an excel file from url

I'm having the following code that I'm using to load, read, write and download an excel file.
//include PHPExcel library
require_once "Classes/PHPExcel/IOFactory.php";
//load Excel template file
$objTpl = PHPExcel_IOFactory::load("excel.xls");
$objTpl->setActiveSheetIndex(0); //set first sheet as active
$objTpl->getActiveSheet()->setCellValue('C2', date('Y-m-d')); //set C1 to current date
$objTpl->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //C1 is right-justified
$strData = $objTpl->getActiveSheet()->getCell('C3')->getValue();
$strData .= $objTpl->getActiveSheet()->getCell('C4')->getValue();
$objTpl->getActiveSheet()->setCellValue('C3', 'It\'s working');
$objTpl->getActiveSheet()->setCellValue('C4', 'Dynamic excel read and writing');
$objTpl->getActiveSheet()->setCellValue('C6', 'Data read: C3 = '.substr($strData,0,1).' and C4 = '.substr($strData,1,1));
$objTpl->getActiveSheet()->getStyle('C4')->getAlignment()->setWrapText(true); //set wrapped for some long text message
$objTpl->getActiveSheet()->getColumnDimension('C')->setWidth(40); //set column C width
$objTpl->getActiveSheet()->getRowDimension('4')->setRowHeight(120); //set row 4 height
$objTpl->getActiveSheet()->getStyle('A4:C4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP); //A4 until C4 is vertically top-aligned
//prepare download
$filename=mt_rand(1,100000).'.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5'); //downloadable file is in Excel 2003 format (.xls)
$objWriter->save('php://output'); //send it to user, of course you can save it to disk also!
My problem is that I want to load the excel file from a different source(url,stream), not from the local directory
Simply save the file to your server and then read it.
file_put_contents('excel.xls',
file_get_contents('https://www.myweburl.com/spreadsheets.xls')
);
$objTpl = PHPExcel_IOFactory::load("excel.xls");

Resources