Unable to change date format in Excel using PHP - php

I am writing lots(around 900 rows) of data into a .xls file using class.writeexcel_worksheet.inc.php PHP class. All data written into excel is treated as simple text, even date and time stamps.
Now the problem is while filtering for dates in excel, there is no filter on for months or year. Since all cell values are simple text. Is there any way to format my cell to date data type while creating excel through PHP code?
CODE:
<?php
require_once "class.writeexcel_workbookbig.inc.php";
require_once "class.writeexcel_worksheet.inc.php";
require_once "db_params.php";
if(isset($_POST['submit']))
{
$heure = date("H_i");
$fname = tempnam("/tmp", $date."_".$heure.".xls");
$workbook = &new writeexcel_workbookbig($fname);
$worksheet = &$workbook->addworksheet();
$mainheading =& $workbook->addformat();
$mainheading->set_color('white');
$mainheading->set_pattern(0x1);
$mainheading->set_align('center');
$mainheading->set_border_color('black');
$mainheading->set_border(1);
$mainheading->set_merge();
$worksheet->write("A1", "Observation", $mainheading, $border2);
$worksheet->set_column(0, 50, 18);
$worksheet->freeze_panes(2, 0); # 1 row
$worksheet->merge_cells("A1:L1");
$heading =& $workbook->addformat();
$heading->set_color('white');
$heading->set_align('center');
$heading->set_align('vcenter');
$worksheet->set_column(0, 50, 18);
//$worksheet->set_outline();
$worksheet->set_margins(2);
# Create a border format
$border1 =& $workbook->addformat();
$border1->set_color('black');
$border1->set_pattern(0x1);
$border1->set_fg_color('white');
$border1->set_border_color('black');
$border1->set_border(1);
$border1->set_text_wrap();
$col=0;
$query = "SELECT * from Incidents";
$res=sqlsrv_query($conn,$query,array(), array('Scrollable'=>SQLSRV_CURSOR_STATIC));
$Entete1 = array("Incident ID - Hyperlink to AR" , "Reported Date", "Service", "Priority", "Operational Categorization Tier 1", "Summary", "Assignment Date", "Status", "Last Assigned Group", "Resolution Status", "Time bef. first assignment", "Number of assignments");
foreach($Entete1 as $value) {
$worksheet->write(1, $col, $value,$heading);
$col++;
}
$col=0;
$Entete11 = array("IncidentID", "ReportDate", "Service", "Priority", "OperationalCategoryT1", "Summary", "AssignmentDate", "Status", "LastAssignedGroup", "ResolutionStatus", "AcknowledgmentTime", "NoOFAssignment", "Team", "Remarks", "RemarkCategory" , "PloneforgeNo" ,"ProdCategorisationT1", "ProdCategorisationT2", "ProdCategorisationT3", "Urgency", "Impact", "Resolved_date", "Category_tier1", "ResolutionDetails", "Name", "LastResolvedDate", "Resolution", "OLAStatus", "OLAUpTime", "ReopenedDate", "StatusReason", "BucketDate", "OLAProgress", "DueDateTime", "GoalTime");
foreach($Entete11 as $value)
{
$x=2;
$y=2;
for( $position = SQLSRV_SCROLL_FIRST ; ($row=sqlsrv_fetch_array($res, SQLSRV_FETCH_BOTH, $position)) ; $position = SQLSRV_SCROLL_NEXT )
{
$chaine = strip_tags($row[$value]);
$worksheet->write($x, $col, $chaine, $border1);
$x++;
}
$col++;
}
$workbook->close();
header("Content-Type: application/x-msexcel; name=".$date."_".$heure.".xls");
header("Content-Disposition: inline; filename=".$date."_".$heure.".xls");
$fh=fopen($fname, "rb");
fpassthru($fh);
unlink($fname);
}
?>

Related

How to conditionally add a column on spreadsheet?

How can i add spreadsheet column conditionally, such as if the user wants to include particular column? I made this code:
$spreadsheet->getActiveSheet()
->setCellValue('A1', "SAMPLE HEADING")
->setCellValue('A2', "Sampling Report")
->setCellValue('A3', Date::PHPToExcel($dateTimeNow))
->setCellValue('A4', "Recipient #")
->setCellValue('B4', "Recipient Name")
->setCellValue('C4', "Date of Birth")
->setCellValue('D4', "Gender");
Now, if for example the user wants only Recipient # or Recipient Name etc. How can i achieve such functionality?
You will need to use if conditions and then use logic to calculate the cell position accurately.
$alphas = range('A', 'Z'); //Delcare Range
$includeRecipient = true; // Flag to decide if Recipient # is requierd
$includeRecipientName = false; // Flag to decide if Recipient Name is not required
$spreadsheet->getActiveSheet()
->setCellValue('A1', "SAMPLE HEADING")
->setCellValue('A2', "Sampling Report")
->setCellValue('A3', Date::PHPToExcel($dateTimeNow));
$cell = '';
if( $includeRecipient ) {
//Can move the following block in a function
if (empty ( $cell) ) {
$cell = current($alphas); //Gives A if empty
} else {
$cell = next($alphas); //Will give next in $range
}
$spreadsheet->setCellValue( $cell . '4', "Recipient #")
}
if( $includeRecipientName ) {
if (empty ( $cell) ) {
$cell = current($alphas); //Gives A if empty
} else {
$cell = next($alphas); //Will give next value in $range
}
$spreadsheet->setCellValue( $cell . '4', "Recipient Name")
}
if (empty ( $cell) ) {
$cell = current($alphas); //Gives A if empty
} else {
$cell = next($alphas); //Will give next value in $range
}
$spreadsheet->setCellValue('C4', "Date of Birth")
->setCellValue('D4', "Gender");

Table MultiCell in FPDF

I am currently using FPDF to output data into a table, however i am running into issues with table cell wrapping.
My current table function is below:
function ImprovedTableCol2($header, $data, $cols ,$colWidth1, $colWidth2, $tableHeader, $closeTable, $fontSize, $icon)
{
// Table Header
if ($tableHeader==true) {
$this->SetFontSize(12);
$this->Cell(90,7,$header[0],1,0,'L');
$this->Cell(90,7,$header[1],1,0,'L');
$this->Ln();
}
// Table body
$this->SetFontSize($fontSize);
$this-> MultiCell(90,6,$data[0],'LRB');
$this->MultiCell(90,6,$data[1],'LRB');
$this->Ln();
}
My table page is as follows:
$pdf->AddPage();
$pdf->SetFont('Arial','B');
$pdf->SetFontSize(18);
$pdf->Cell(0,10,'Method Statement','B',1,'L');
$pdf->SetFont('');
$pdf->SetFontSize(10);
$pdf->Ln();
$header = array('', '');
$intTotalSCRows = "{method_statement:total_rows}";
$arrSafetyCheck = array();
array_push($arrSafetyCheck, array(
"day" => "{method_statement:day}",
"statement" => "{method_statement:statement}",
"engineer" => "{method_statement:engineer}",
"count" => "{method_statement:count}")
);
foreach ($arrSafetyCheck as $key => $list) {
if ($list['count']=="1") {
$data = array(utf8_decode($list['day']), $list['statement']);
$pdf->ImprovedTableCol2($header,$data,2,130,50,true,false,9,false);
} else if ($list['count']==$intTotalSCRows) {
$data = array(utf8_decode($list['day']), $list['statement']);
$pdf->ImprovedTableCol2($header,$data,2,130,50,false,true,9,false);
} else {
$data = array(utf8_decode($list['day']), $list['statement']);
$pdf->ImprovedTableCol2($header,$data,2,130,50,false,false,9,false);
}
}
The MultiCell function does wrap the text, but i cannot get the 2 table columns to sit side by side.
You will need to manually set the position of the cell (see the updated method below)
function ImprovedTableCol2($header, $data, $cols ,$colWidth1, $colWidth2, $tableHeader, $closeTable, $fontSize, $icon)
{
// Table Header
if ($tableHeader==true) {
$this->SetFontSize(12);
$this->Cell(90,7,$header[0],1,0,'L');
$this->Cell(90,7,$header[1],1,0,'L');
$this->Ln();
}
// Table body
$this->SetFontSize($fontSize);
// Get X,Y coordinates
$x = $this->GetX();
$y = $this->GetY();
$this->MultiCell(90,6,$data[0],'LRB');
// update the X coordinate to account for the previous cell width
$x += 90;
// set the XY Coordinates
$this->SetXY($x, $y);
$this->MultiCell(90,6,$data[1],'LRB');
$this->Ln();
}

General input/output error ? how to solve when the excel sheet?

Yii::import('application.extensions.phpexcel1.JPhpExcel');
$xls = new JPhpExcel('UTF-8', false, 'My Test Sheet');
$xls->addArray($sheet_generation);
$xls->generateXML('my-test');
In controller :
$get_user_info=$model->userInfo();
###### Sheet generation
$sheet_generation=$model->sheetInfo($get_user_info,$month,$year);
In model:-
public function sheetInfo($user_info,$sel_month,$sel_year)
{
$cnt=0;
foreach($user_info as $key => $line) {
$cnt=$cnt+1;
$linearr = $line;
//$linearr['heading']='';
//$linearr['imagess']='';
//array_push($linearr, "apple", "raspberry");
//print_r($linearr); exit;
$p=$line['Place'];
$place=Sheet::getWorkin($p);
$userid=$line['id'];
// Total present days
$no_days=Sheet::getPresent($userid,$sel_month,$sel_year);
$disti=$line['Designation'];
//designation names...............
$designation=Sheet::detDesignationName($disti);
/// Department name display..............
$d=$line['Department'];
$depart=Sheet:: getDepartmantName($d);
// Holiday
$holiday=Sheet::getHolidayDat($sel_month,$sel_year);
$approval=2;
$leave_count=Sheet::getLeaveCount($userid,$sel_month,$sel_year,$approval);
###### sunday leave count
$sunday=Sheet::sunday_count($sel_month,$sel_year);
########saturday count
$sat_count=Sheet::saturday_count($sel_month,$sel_year);
$sat_sunday_count=Sheet::weekday_count($userid,$sel_month,$sel_year);
//$heading="Attendance Report January 2014";
//$linearr['heading']=Yii::app()->theme->baseUrl/images/."favicon.ico";
//$linearr['Sno']=$cnt;
$linearr['Place']=$place;
$linearr['Designation'] =$designation;
$linearr['Department'] =$depart;
$sum_present=$sum_present+$no_days; // sum of present days....................
$linearr['present'] =$no_days;
$linearr['holiday'] =$holiday;
$linearr['leave'] =$leave_count;
$linearr['weekoffice'] =$sat_sunday_count;
$linearr['lop'] =0;
$resarr[] = $linearr;
}
//print_r($resarr); exit;
return $resarr;
}

How to export data to an excel file using PHPExcel

I have taken the source code from limesurvey and have added the PHPExcel library to my limesurvey code to export data to an excel file after you click a link. Currently the excel file opens with some dummy data in it with no problems. I need to be able to add data dynamically from the web server after a user types in survey information. I have looked into some sites I have found but I havent had much luck. Can anyone help me out?
EDIT
<?php
$dbhost= "mysql"; //your MySQL Server
$dbuser = "survey"; //your MySQL User Name
$dbpass = "password"; //your MySQL Password
$dbname = "database";
//your MySQL Database Name of which database to use this
$tablename = "questions"; //your MySQL Table Name which one you have to create excel file
// your mysql query here , we can edit this for your requirement
$sql = "Select * from $table ";
//create code for connecting to mysql
$Connect = #mysql_connect($dbhost, $dbuser, $dbpass)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($dbname, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
error_reporting(E_ALL);
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
If you've copied this directly, then:
->setCellValue('B2', Ackermann')
should be
->setCellValue('B2', 'Ackermann')
In answer to your question:
Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.
The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.
EDIT
An extremely simplistic example:
// Create your database query
$query = "SELECT * FROM myDataTable";
// Execute the database query
$result = mysql_query($query) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){
// Set cell An to the "name" column from the database (assuming you have a column called name)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']);
// Set cell Bn to the "age" column from the database (assuming you have a column called age)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']);
// Increment the Excel row counter
$rowCount++;
}
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx');
EDIT #2
Using your existing code as the basis
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Try the below complete example for the same
<?php
$objPHPExcel = new PHPExcel();
$query1 = "SELECT * FROM employee";
$exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Sr.Number","Employee Login","Employee Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysql_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['employeelogin'];
array_push($tmparray,$employeelogin);
$employeename = $res1['employeename'];
array_push($tmparray,$employeename);
array_push($sheet,$tmparray);
}
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="name.xlsx"');
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
//make first row bold
$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel.
Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
I currently use this function in my project after a series of googling to download excel file from sql statement
// $sql = sql query e.g "select * from mytablename"
// $filename = name of the file to download
function queryToExcel($sql, $fileName = 'name.xlsx') {
// initialise excel column name
// currently limited to queries with less than 27 columns
$columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
// Execute the database query
$result = mysql_query($sql) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// fetch result set column information
$finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter
$columnlenght = 0;
foreach ($finfo as $val) {
// set column header values
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
}
// make the column headers bold
$objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);
$rowCount++;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
for ($i = 0; $i < $columnLenght; $i++) {
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
}
$rowCount++;
}
// set header information to force download
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('php://output');
}
// gl and gl2 excel file Export Program
public function glExcelFileExport()
{
$from_date1 = $this->input->post('from_date1');
$to_date1 = $this->input->post('to_date1');
$account_number = $this->input->post('account_number');
$glnames = $this->input->post('glnames');
$sql = "SELECT * FROM ut_sbi_reco_rungl WHERE value_date between '".$from_date1."' AND '".$to_date1."' ";
$result = $this->db->query($sql)->result_array();
if(count($result)>0)
{
require FCPATH . 'vendor/autoload.php';
$object = new PHPExcel();
$prestasi = $object->setActiveSheetIndex(0);
//manage row hight
$object->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
// Excel Heading Description
if($glnames == 'gl1') {
//style alignment
$styleArray = array(
'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
),
);
$object->getActiveSheet()->getStyle('A1:U1')->getFont()->setBold(true);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray);
//border
$styleArray1 = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
//background
$styleArray12 = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => 'FFFF00',
),
),
);
//freeepane
$object->getActiveSheet()->freezePane('A2');
//column width
$object->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('F')->setWidth(12);
$object->getActiveSheet()->getColumnDimension('G')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('H')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$object->getActiveSheet()->getColumnDimension('L')->setWidth(10);
$object->getActiveSheet()->getColumnDimension('M')->setWidth(12);
$object->getActiveSheet()->getColumnDimension('N')->setWidth(25);
$object->getActiveSheet()->getColumnDimension('O')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('P')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('R')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('S')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('T')->setWidth(25);
$object->getActiveSheet()->getColumnDimension('U')->setWidth(15);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray1);
$object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray12);
$object->getActiveSheet()->getStyle('I')->getNumberFormat()->setFormatCode("0.00");
$table_columns = array("SRL", "Scheme", "Tran Type", "App Refer", "OTH Refer",
"Account", "Name", "Value Date", "Amount", "Pay Category", "Rev Flg",
"Security", "Cheque Number", "SCH", "Book Date", "Cheque Date",
"Reg Id", "Inputter", "Narration", "FL", "Batch Number");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
}
if($glnames == 'gl2') {
//style alignment
$styleArray = array(
'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
),
);
$object->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray);
//border
$styleArray1 = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
//background
$styleArray12 = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array(
'rgb' => 'FFFF00',
),
),
);
//freeepane
$object->getActiveSheet()->freezePane('A2');
//column width
$object->getActiveSheet()->getColumnDimension('A')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$object->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray1);
$object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray12);
$object->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode("0.00");
$table_columns1 = array("Account", "Name", "Amount");
$column1 = 0;
foreach($table_columns1 as $field1)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column1, 1, $field1);
$column1++;
}
}
// List of column names
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$prestasi->getDefaultStyle()->applyFromArray($style);
if($glnames == 'gl1') {
// Gl1 Query
$excel_row = 2;
for ($kk=0;$kk<count($account_number);$kk++)
{
$account_number2 = $account_number[$kk];
$gl1Arr = $this->ut_gl_model->getDisplayGl1Query($account_number2,$from_date1,$to_date1);
foreach($gl1Arr as $row)
{
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $row['srl']);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row['scheme']);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row['tran_type']);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row['app_refer']);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row['oth_refer']);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row['account']);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row['name']);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, (isset($row['value_date']) && $row['value_date']!='0000-00-00')?date('d/m/Y',strtotime($row['value_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $row['amt']);
$object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row, $row['pay_catego']);
$object->getActiveSheet()->setCellValueByColumnAndRow(10, $excel_row, $row['rev_flg']);
$object->getActiveSheet()->setCellValueByColumnAndRow(11, $excel_row, $row['security']);
$object->getActiveSheet()->setCellValueByColumnAndRow(12, $excel_row, $row['chq_number']);
$object->getActiveSheet()->setCellValueByColumnAndRow(13, $excel_row, 'y');
$object->getActiveSheet()->setCellValueByColumnAndRow(14, $excel_row, (isset($row['book_date']) && $row['book_date']!='0000-00-00')?date('d/m/Y',strtotime($row['book_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(15, $excel_row, (isset($row['chq_date']) && $row['chq_date']!='0000-00-00')?date('d/m/Y',strtotime($row['chq_date'])):'');
$object->getActiveSheet()->setCellValueByColumnAndRow(16, $excel_row, $row['reg_id']);
$object->getActiveSheet()->setCellValueByColumnAndRow(17, $excel_row, $row['inputter']);
$object->getActiveSheet()->setCellValueByColumnAndRow(18, $excel_row, $row['narration']);
$object->getActiveSheet()->setCellValueByColumnAndRow(19, $excel_row, '');
$object->getActiveSheet()->setCellValueByColumnAndRow(20, $excel_row, '');
$excel_row++;
}
}
// Excel Download Logic
$downloadFile = 'gl1_'.date('Ymd').'.xlsx';
$prestasi->setTitle("Gl1 Dump");
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$downloadFile.'" ');
$object_writer->save('php://output');
}
$excel_row1 = 2;
if($glnames == 'gl2') {
// Gl2 Query
for ($jj=0;$jj<count($account_number);$jj++)
{
$account_number3 = $account_number[$jj];
$gl2Arr = $this->ut_gl_model->getDisplayGl2Query($account_number3,$from_date1,$to_date1);
foreach($gl2Arr as $row1)
{
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row1, $row1['account']);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row1, $row1['name']);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row1, $row1['amount']);
// $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row1, $row1['value_date']);
$excel_row1++;
}
}
// Excel Download Logic
$prestasi->setTitle("Gl2 Dump");
$downloadFile2 = 'gl2_'.date('Ymd').'.xlsx';
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$downloadFile2.'" ');
$object_writer->save('php://output');
}
}
else
{
$this->session->set_flashdata('error', 'Data not found.');
redirect(site_url('sbi-reco/run-gl'));
}
}

Is there a free PHP Wrapper or backend script for a JQUERY Grid Control (JQGRID or Datatables)

I am looking to implement a best-practice JQUERY grid control, with a PHP backend. I want it to be able to support large datasets, and inline cell editing.
I am struggling to find a PHP backend script which is integrated with the control and abstracts away the complexities of this stuff. I want to be able to implement a grid based on an underlying MYSQL table with a minimum of configuration. Really I can't be the only one who wants to be able to specify basic database details and table/sql and have an operating grid.
JQGrid has a paid PHP script backend you can use which sounds like what I want...only its expensive.
http://www.trirand.net/documentation/php/index.htm
There's also a cheaper thing trying to do the same thing, but it doesn't work.
http://azgtech.wordpress.com/2010/08/01/jqgrid-php-datagrid/
I've also looked at DataTables, but once you add the inline-editing capabilities, developing the PHP backend started becoming its own project.
I have spend ages researching this, and mucking about with various solutions.
Does anybody know of a powerful, free, easy to use solution which has a complete PHP backend script?
I've included some of the description of the paid JQGrid PHP control, which contains the kind of functionality I'm looking for.
JQGRid PHP
This is a brand new product created for PHP developers and teams that radically decreases development time with jqGrid and makes it fun and easy. The product will be offered with commercial licenses that will include fast and accurate technical support, source code and subscription based benefits.
Highlight points include:
- all functionality jqGrid has is supported
- no need for tricky javascript – everything is handled in PHP
- the PHP component automatically handles data retrieval, paging, sorting, searching and all CRUD operations (create, read, update, delete). No need for custom code.
- you can have a fully functional grid with just a few lines of PHP
- export to Excel is supported
- database engines supported: MySql, Postgre SQL, Microsoft SQL server
Have you checked out phpGrid. It's a PHP jqgrid wrapper. It just two lines of code to get started. Is that something you are looking for?
$dg = new C_DataGrid(“SELECT * FROM orders”, “orderNumber”, “orders”);
$dg -> display();
I wrote this small library a while back as a a booze filled weekend project a while ago, it's a bit messy but it'll provide some of the default back end functionality that you're looking for.]
<?php
/*
Grid.php
Lirbary of function for the translation of Array() objects into json
*/
/*--- INCLUDE DEPENDENCIES ---*/
include_once "lib/sql.php";
/*--- HEADER UPDATE ---*/
header("Content-type: application/json");
/*--- GLOBALS ---*/
/*Default sort order*/
define('GRID_DEFAULT_SORT_ORDER', "ASC");
/*Default page index*/
define('GRID_DEFAULT_PAGE', 0);
/*Default results per page*/
define('GRID_DEFAULT_RP', 15);
/*--- FUNCTIONS ---*/
/*
Build Grid Queries
desc: Build the queries used to provide the grid results
params:
$select: 2D associative array
field: name of field
alias: field alias
$from: table data is to be selected from
return: An array containing the query to select entries and the query to get the result count
*/
function buildGridQueries($select, $from)
{
/*Create select statement*/
$selectStr = "SELECT ";
for($i = 0; $i < count($select);$i++){
/*append field name to str*/
$selectStr .= $select[$i]['field'];
/*If an alias has provided*/
if(isset($select[$i]['alias']))
$selectStr .= " AS '". $select[$i]['alias']. "'";
/*if current field is not the last */
if($i < count($select) - 1)
$selectStr .= ", ";
}
/*Create from statement*/
$fromStr = " FROM $from";
/*Set sort by value by $_POST value if available or by $select[0][field]*/
$sortStr = " ORDER BY ";
if(isset($_POST['sortname']))
if($_POST['sortname'] == "undefined")
$sortStr .= $select[0]['field'];
else
$sortStr .= $_POST['sortname'];
else
$sortStr .= $select[0]['field'];
/*Set sort order by $_POST if available or by ASC*/
if(isset($_POST['sortorder']))
$sortStr .= " ". $_POST['sortorder'];
else
$sortStr .= " ". GRID_DEFAULT_SORT_ORDER;
/*Set query conditional WHERE statement if passed*/
$queryStr = "";
if(isset($_POST['qtype'])&&isset($_POST['query']))
if($_POST['query']!= "")
$queryStr .= " WHERE ". $_POST['qtype']. " LIKE '%" . $_POST['query']. "%' ";
/*Create limit statement by passed values or by defaults*/
$limitStr = " LIMIT ";
if(isset($_POST['page']))
if($_POST['rp'])
$limitStr .= ($_POST['page'] - 1) * $_POST['rp'] . ",". $_POST['rp'];
else
$limitStr .= $_POST['page'] . ", ". GRID_DEFAULT_RP;
else
$limitStr .= GRID_DEFAULT_PAGE. ", ". GRID_DEFAULT_RP;
/*return queries array*/
return Array("query" => $selectStr. $fromStr. $queryStr. $sortStr. $limitStr,
"count" => "SELECT COUNT(id) AS 'total' $fromStr $queryStr ");
}
/*
Commit Data
desc: Commit data edits (Passed by a client side flexigrid object
params:
$table: table name
$rows: rows array of data to be committed
$index: Field name of index column, used in where statement
return: An array of update results for each passed row;
*/
function commitGridData($table,$rows,$indexField, $sqlConnection)
{
/*Declare return array*/
$return = Array();
/*With every row which is to be committed*/
foreach($rows as $row){
/*Create update statement base and iterate through cells*/
$statement = "UPDATE $table SET ";
for($i = 0;$i<count($row['fields']);$i++){
/*If value is a string check to see if it's a date*/
if(!is_numeric( $row['fields'][$i]['value'])){
/*Encapsulate str it isn't a date, convert to time if it is*/
$val = "'". $row['fields'][$i]['value']. "'";
}else
$val = $row['fields'][$i]['value'];
/*Append field name and value to statement*/
$statement .= $row['fields'][$i]['field'] . "=". $val;
/*Append delimiter to the statement if this cell is not the last in $orw*/
if($i<count($row['fields']) - 1)
$statement .= ", ";
}
if($row['entryIndex'] < 0)
$row['entryIndex'] = mysqlCreateEntry($table, $sqlConnection);
/*Append where statement*/
$statement .= " WHERE $indexField = ". $row['entryIndex'];
/*Update row information*/
$return[] = Array("id" => $row['tableId'], "success" => mysqlQuery($statement, $sqlConnection), "error" => mysql_error());
}
/*Return result set*/
return $return;
}
/*
Generate Grid Array
desc: generate Array object which is compatible with FlexiGrid when it is json encoded
params:
$queries: Queries for retrieving data entries and result set size
$fields: 2D associative array or false to prevent inline generation
field: name of field
alias: field alias
$sql: An Sql connection identifier
return: An array of FlexiGrid properties
*/
function generateGridArray($queries, $fields, $sqlConnection)
{
/*Get the total number of results matching the search query*/
$res = mysqlQuery($queries['count'], $sqlConnection);
$total = mysql_fetch_assoc($res);
/*Get matching result set*/
$res = mysqlQuery($queries['query'], $sqlConnection);
/*Create result FlexGrid-compatible Array*/
$data =Array(
"page" => (isset($_POST['page']))? $_POST['page']: 1,
"total" => $total['total'],
"width" => 500,
"height" => (isset($_POST['rp']))? $_POST['rp']: mysql_num_rows($res) * 20 + 45,
"title" => " ",
"propertyCount" => count($fields),
"rows" => sqlToGridRows($fields, $res));
/*If initial request (no $_POST equals passive data collection by the client side*/
if(count($_POST) < 1 ){
$data['colModel'] = sqlToGridColModel($fields, $res);
$data['searchitems'] = arrayToGridSearchItems($fields);
}
/*Return*/
return $data;
}
function sqlToGridRows($fields, $sqlResult)
{
/*Identify the entry index column*/
$fieldTypes = Array();
foreach($fields as $field){
/*if the field is the entry index*/
if(isset($field['entryIndex']))
/*Set field as entryIndex*/
$entryIndexCol = (isset($field['alias']))? $field['alias']: $field['field'];
}
/*Iterate through result set*/
$return = Array();
for($i = 0;$i < mysql_num_rows($sqlResult);$i++){
/*Get entry data*/
$row = mysql_fetch_assoc($sqlResult);
/*modify values based on fieldType*/
foreach($fields as $field){
/*If the fieldType value is set, no changes otherwise*/
if(isset($field['fieldType'])){
/*Field type specific formating*/
switch ($field['fieldType']){
/*Format field as a date*/
case "date":
/*Update by either field label if the label key exists in row or use alias*/
if(isset($row['field']))
$row[$field['field']] = date("d/m/Y", $row[$field['field']]);
else
$row[$field['alias']] = date("d/m/Y", $row[$field['alias']]);
break;
case "time":
if(isset($row['field']))
$row[$field['field']] = date("H:i", $row[$field['field']]);
else
$row[$field['alias']] = date("H:i", $row[$field['alias']]);
break;
}
}
}
/*if the entry index column was identified*/
if(isset($entryIndexCol)){
/*Set entryIndex value*/
$entryIndex = $row[$entryIndexCol];
/*remove the entryIndexCol from the row*/
unset($row[$entryIndexCol]);
}else
/*Set the entry index as the default*/
$entryIndex = $i;
/*Create entry*/
$entry = Array("id" => $i,
"entryIndex" => $entryIndex,
"cell" => $row);
/*iterate $fields and replace aliased keys with field names*/
for($m = 0;$m < count($fields);$m++){
/*if field has an alias update the key value*/
if(isset($fields[$m]['alias'])){
/*Replace and rebuild field->cell*/
$cell = Array();
foreach($entry['cell'] as $key => $val){
/*if culprit cell change key*/
if($key == $fields[$m]['alias'])
$cell[$fields[$m]['field']] = $val;
else
$cell[$key] = $val;
}
/*Update entry->cell value*/
$entry['cell'] = $cell;
}
}
/*Map sql result to grid table row structure*/
$return[] = $entry;
}
/*Return grid-ready array*/
return $return;
}
function sqlToGridColModel($fields, $sqlResult)
{
/*Iterate through result set*/
$return = Array();
for($i = 0;$i < mysql_num_fields($sqlResult);$i++){
/*Replace aliased cell name attributes with associted field name*/
$alias = mysql_field_name($sqlResult, $i);
$name = false;
$isEntryIndex = false;
for($m = 0;$m < count($fields);$m++){
/*If current field has an alias which equals $name, replace name with $field[[$m]['field']*/
if(isset($fields[$m]['alias'])){
/*if field has an alias*/
if($fields[$m]['alias'] == $alias){
$name = $fields[$m]['field'];
}
}else{
if($fields[$m]['field'] == $alias){
$name = $fields[$m]['field'];
}
}
/*Add field data etc*/
$fieldData = false;
if(isset($fields[$m]['fieldType'])){
/*Get field type*/
$fieldType = $fields[$m]['fieldType'];
/*Attach select options to field if available*/
if($fieldType == "select")
/*Set default field type*/
$fieldData = $fields[$m]['fieldData'];
}else
$fieldType = "input";
/*If the field is the entry index flag it for exclusion*/
if($name){
/*If the field is the entry index*/
if(isset($fields[$m]['entryIndex']))
$isEntryIndex = true;
/*Exit for loop*/
$m = count($fields);
}
}
/*If no name was set (alias is also name)*/
if(!$name)
$name = $alias;
/*If the field is to be included in the column model*/
if($isEntryIndex == false){
/*Append column data to return*/
$return[] = Array("display" => $alias, "name" => $name,
"width" => 200, "sortable" => "true",
"fieldType" => $fieldType, "fieldData" => $fieldData);
}
}
/*Return grid-ready array*/
return $return;
}
function arrayToGridSearchItems($fields)
{
/*iterate fields*/
$return = Array();
for($i = 0;$i < count($fields);$i++){
/*if field has an alias use it for the display name*/
$alias = (isset($fields[$i]['alias']))? $fields[$i]['alias']: $fields[$i]['field'];
/*If field is not the entry index*/
if(!isset($fields[$i]['entryIndex']))
/*Create searchitem and append to return*/
$return[] = Array("display" => $alias,
"name" => $fields[$i]['field'],
"isdefault" => ($i == 0)? "true": "false");
}
/*return*/
return $return;
}
?>
This is designed to allow the development of Grid data tables using a standard template, Below is an example template.
<?php
/*include grid lib*/
include "lib/grid.php";
/*Create sql connection*/
$sqlConnection = mysqlConnect($_USER->sqlUser, $_USER->sqlPass);
/*----------------------*/
/*--- Create fieldData ---*/
$userTypes = Array(
Array("value" =>0, "text" => "Staff"),
Array("value" => 1, "text" => "Manager"));
/*----------------------*/
/*---
Define selection array
Create field selection and rules Array. Defines output.
---*/
$array = Array();
$array[] = Array("field" => "id", "entryIndex" => true); /*Entry index is the Sql row id, isn't show in table but is used for commits*/
$array[] = Array("field" => "username", "alias" => "User Name");
$array[] = Array("field" => "name", "alias" => "Name");
$array[] = Array("field" => "address", "alias" => "Address");
$array[] = Array("field" => "postcode", "alias" => "Postcode");
$array[] = Array("field" => "tel", "alias" => "Telephone");
$array[] = Array("field" => "mobile", "alias" => "Mobile");
$array[] = Array("field" => "email", "alias" => "Email Address");
$array[] = Array("field" => "user_type", "alias" => "User Type", "fieldType" => "select", "fieldData" => $userTypes);
$table = "staff";
/*---
Commit data template
Inlcude a the following if
---*/
/*If an action is to be carried out prior to data load*/
if(isset($_GET['method'])){
/*If transaction is a data commit*/
if($_GET['method'] == "commit"){
/*Check that edit requests were sent*/
if(isset($_POST['rows'])){
/*Pre-update validation*/
foreach($_POST['rows'] as &$row){
/*Any preprocessing for entries prior to commit*/
}
echo json_encode(commitGridData($table, $_POST['rows'], "id", $sqlConnection));
exit;
}
}
}
/*Buildd queries - Opportunity to debug queries, alternatively pass to generateGridArray*/
$queryStrs = buildGridQueries($array, "staff");
/*Generate grid data*/
$resArray = generateGridArray($queryStrs, $array, $sqlConnection);
/*Pre grid build extend and/or alter settings*/
if(count($_POST) < 1){
$resArray['buttons'] = Array(Array("name" => "Add", "bclass" => "add", "onpress" => "add"));
$resArray['title'] = "Staff Details";
$resArray['editable'] = true;
}
echo json_encode($resArray);
exit;
?>
I've extended Flexgrid to accommodate for field formatting, committing data and adding field events but I can't for the life of me find it. I'll post it if I do.
Disclaimer: $_POST is used recklessly throughout grid.php. It is recommended that it's replaced with something more fitting.
I've just found a github project which seems to be really great for this: https://github.com/lampjunkie/php-datatables
It provides a wrapper for Jquery Datatables plugin, handles the initial setup and the ajaq data feeds also. It has an object-oriented approach and seems to be very logically designed.
You also can find an example project in the package.

Categories