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!
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');
?>
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;
?>
So, i have a form which able to read excel files and save to database by uploading an excel file. It is fine when i upload .xls file, but not with the .xlsx. Here is the code:
echo ' File berhasil diupload => '.$dok['file_name']; //success to echo uploaded .xlsx file
//EXCEL READING, load library
$this->load->library('excel');
//Identify the type of $inputFileName
$inputFileType = PHPExcel_IOFactory::identify(FCPATH."/asset/files/uploads/".$dok['file_name']);
//Create a new Reader of the type that has been identified
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
//Failed to echo (if i upload .xlsx file)
echo 'input file type => '.$inputFileType;
//begin to read excel file
$this->excel = $objReader->load(FCPATH."/asset/files/uploads/".$dok['file_name']);
$objWorksheet=$this->excel->getActiveSheet();
$highestRow=$objWorksheet->getHighestRow();
$highestColumm = $objWorksheet->getHighestColumn();
$highestColumm++;
//jika option timpa, maka delete semua data
if($timpa == 'y')
{
$this->_model->del_table_mcactivity();
}
//read per row and save to database
foreach($this->excel->getWorksheetIterator() as $worksheet){
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns= ord($highestColumn) - 64;
for ($row = 2; $row <= $highestRow; ++ $row) {
$kodemak = $objWorksheet->getCell("A$row")->getValue();
$tahun = $objWorksheet->getCell("B$row")->getValue();
$unitkerja = $objWorksheet->getCell("C$row")->getValue();
$nomorkegiatan = $objWorksheet->getCell("D$row")->getValue();
$kegiatan = $objWorksheet->getCell("E$row")->getValue();
$noskkegiatan = $objWorksheet->getCell("F$row")->getValue();
$jenis = $objWorksheet->getCell("G$row")->getValue();
$pagu = $objWorksheet->getCell("H$row")->getValue();
//get for refworkingunit id
$idrefworkingunit = $this->_model->get_workingunit_by_name($unitkerja);
//filtering for budget
$budget = $this->filter_budget($pagu);
//grouping variable to save in database
$activity_data = array('year'=>$tahun, 'idrefworkingunit'=>$idrefworkingunit, 'activitynumber'=>$nomorkegiatan, 'activityname'=>$kegiatan, 'activityreference'=>$noskkegiatan, 'accountnumber'=>$kodemak, 'traveltype'=>$jenis, 'budget'=> $budget);
//insert to database
$this->db->insert('mcactivity', $activity_data);
}
}
I use PHPExcel_IOFactory::identify() to identify the reader should be used. But i think it's failed.I've read this question , then i replace
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
with:
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); but it still doesn't work. Can somebody help me, please ?
XLS and XLSX are two different files types.
XLS
$this->load->library('Excel5');
XLSX
$this->load->library('Excel2007');
Consult the documentation "PHPExcel User Documentation - Reading Spreadsheet Files.doc" that comes with PHPExcel. Page 1 explains the formats, and Page 4 explains different ways of telling PHPExcel what file type to handle.
There are multiple lines where the reference to "Excel2007" and "Excel5" might occur.
Do a search on 'Excel' and not over-look any possibility.
e.g. $objReader = new PHPExcel_Reader_Excel2007(); //was Excel5
Change to _Excel2007 did allow me to read a .xlsx file, but did not break a script that read a .xls file. So there might be backwards compatibility.