How to conditionally add a column on spreadsheet? - php

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");

Related

Compare uploaded data in database and raw CSV data

Here is the code after I uploaded the raw file then tried to validate the raw file with the uploaded file to see if they match:
while ($db_fetch_row = sqlsrv_fetch_array($database_query)){
$db_eid = $db_fetch_row['eid'];
$db_team_lead = $db_fetch_row['team_lead'];
$db_role = $db_fetch_row['role'];
$db_productivity = $db_fetch_row['productivity'];
$db_quality = $db_fetch_row['quality'];
$db_assessment = $db_fetch_row['assessment'];
$db_staffed_hours = $db_fetch_row['staffed_hours'];
$db_kpi_productivity = $db_fetch_row['kpi_productivity'];
$db_kpi_quality = $db_fetch_row['kpi_quality'];
$db_kpi_assessment = $db_fetch_row['kpi_assessment'];
$db_kpi_staffed_hours = $db_fetch_row['kpi_staffed_hours'];
for($row = 2; $row <= $lastRow; $row++) {
$eid = $worksheet->getCell('A'.$row)->getValue();
$team_lead = $worksheet->getCell('C'.$row)->getValue();
$role = $worksheet->getCell('B'.$row)->getValue();
$productivity = $worksheet->getCell('D'.$row)->getValue();
$productivity1 = chop($productivity,"%");
$quality = $worksheet->getCell('E'.$row)->getValue();
$quality1 = chop($quality,"%");
$assessment = $worksheet->getCell('F'.$row)->getValue();
$assessment1 = chop($assessment,"%");
$staffed_hours = $worksheet->getCell('G'.$row)->getValue();
$staffed_hours1 = chop($staffed_hours,"%");
$kpi_productivity = $worksheet->getCell('H'.$row)->getValue();
$kpi_quality = $worksheet->getCell('I'.$row)->getValue();
$kpi_assessment = $worksheet->getCell('J'.$row)->getValue();
$kpi_staffed_hours = $worksheet->getCell('K'.$row)->getValue();
if($db_eid == $eid) {
echo "Raw and Uploaded file Matched";
} else {
echo "Did not match";
}
}
}
The output always didn't match, as you can see below:
Of course it outputs that. Let's think it through:
For every row in the DB, you are checking EVERY row in the CSV. Presumably there is only ONE row in the CSV that has the same ID as the row in the DB, so that means if there are 100 records in the CSV, it will output "no match" 99 times (assuming there is 1 record in the CSV that does match).
One approach is to separate it into a function and attempt to find the matching row, as follows:
// Loop over all DB records
while ($db_fetch_row = sqlsrv_fetch_array($database_query)) {
// call our new function to attempt to find a match
$match = find_matching_row( $db_fetch_row, $worksheet );
// If there's no match, output "didn't find a match"
if ( ! $match ) {
echo '<br>DID NOT FIND A MATCH.';
// If there IS a match, $match represents the row number to use....
} else {
var_dump( $match );
// Do your work on the match data...
$team_lead = $worksheet->getCell('C'.$match)->getValue();
// ...etc
}
}
/**
* Attempt to find a row from the CSV with the same ID as the DB
* record passed in.
*
* #param array $db_fetch_row
* #param mixed $worksheet
*/
function find_matching_row( $db_fetch_row, $worksheet ) {
$db_eid = $db_fetch_row['eid'];
// Youll need to calculate $lastRow for this to work right..
$lastRow = .... ;
// Loop through the CSV records
for($row = 2; $row <= $lastRow; $row++) {
// If the IDs match, return the row number
if($db_eid == $worksheet->getCell('A'.$row)->getValue() ){
return $row;
}
}
// If no match, return FALSE
return FALSE;
}

Unable to change date format in Excel using 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);
}
?>

Symfony2 - Am I handling things in the correct place?

I am in the process of turning my standard PHP project into something built on Symfony2. One part I have is this function
function viewAvailability(){
$db = Database::get();
$active = "Active";
// Fetch all the active alert IDs.
$idListSql = $db->prepare("SELECT DISTINCT id
FROM availability_alert
WHERE alert_status = :active");
$idListSql->bindParam(':active', $active);
$idListSql->execute();
$alerts = array();
// Go through each ID.
while ($idListRow = $idListSql->fetch(PDO::FETCH_ASSOC)) {
$alertId = (int)$idListRow["id"];
// Create the first dimension of the array, using the alert ID as the key.
$alerts[$alertId] = array();
// Fetch all the availability values for this alert.
$availabilitySql = $db->prepare("
SELECT availability, last_updated, class_letter, alert_pseudo, flight_number
FROM availability_alert_availability
WHERE availability_alert_id = {$alertId}
ORDER by class_letter, last_updated");
$availabilitySql->execute();
// Go through each availability result.
while ($aRow = $availabilitySql->fetch(PDO::FETCH_ASSOC)) {
// Fetch the date and hour for this availability row as a string.
$dateString = new DateTime($aRow["last_updated"]);
$dateString = $dateString->format('d M Y H:00');
// Create the second dimension of the array, using the alert pseudo as the key.
if (empty($alerts[$alertId][$aRow["alert_pseudo"]])) {
$alerts[$alertId][$aRow["alert_pseudo"]] = array();
}
// Create the third dimension of the array, using the flight number as the key.
if (empty($alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]])) {
$alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]] = array();
}
// Create the fourth dimension of the array, using the date string as the key.
if (empty($alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]][$dateString])) {
$alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]][$dateString] = array();
}
// Create the fifth dimension of the array, using the class letter as a key, and the
// availability value as the value.
$alerts[$alertId][$aRow["alert_pseudo"]][$aRow["flight_number"]][$dateString][$aRow["class_letter"]] = $aRow["availability"];
}
}
}
This is only part of the function, I then go onto a lot of loops to output the data in a table. Anyways, I have moved my database calls above into my Entities custom repository (using DQL instead).
I then do most of the above working in my controller
public function availabilityAction()
{
$em = $this->getDoctrine()->getEntityManager();
$alerts = $em->getRepository('NickAlertBundle:AvailabilityAlert')->getActiveAlertIds();
$alertsArray = array();
if (!$alerts) {
throw $this->createNotFoundException('Unable to find Availability.');
}
foreach($alerts as $alert){
$alertId = (int)$alert['id'];
$alertsArray[$alertId] = array();
$allAvailability = $em->getRepository('NickAlertBundle:AvailabilityAlert')->getAlertAvailability($alertId);
foreach($allAvailability as $alertAvailability)
{
$dateString = $alertAvailability['lastUpdated'];
$dateString = $dateString->format('d M Y H:00');
if (empty($alerts[$alertId][$alertAvailability['alertPseudo']])) {
$alertsArray[$alertId][$alertAvailability['alertPseudo']] = array();
}
if (empty($alerts[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']])) {
$alertsArray[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']] = array();
}
if (empty($alerts[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']][$dateString])) {
$alertsArray[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']][$dateString] = array();
}
$alertsArray[$alertId][$alertAvailability['alertPseudo']][$alertAvailability['flightNumber']][$dateString][$alertAvailability['classLetter']] = $alertAvailability['availability'];
}
}
return $this->render('NickAlertBundle:Page:availability.html.twig', array(
'alertsArray' => $alertsArray,
));
}
Now it is a lot neater, but I feel there is too much going on in my controller (not sure if this is good or not). The other problem is that I am then passing this filled up array I have to my view. Now I have a complex table layout to create from this array, and I really dont think it should be the job of the view to do this. As an example, this is part of the code I would need to convert within the view
if (!empty($pseudos)) {
foreach ($pseudos as $pseudo => $flights) {
foreach ($flights as $flight => $dates) {
$firstDate = array_pop(array_keys($dates));
echo '<div class="availability_table_container">';
echo "<table class='availability_table'>";
echo "<tr>";
if ($i == 0) {
echo "<th></th>";
}
echo "<th class='pseudo-header'>{$flight}</th>";
echo "</tr>";
echo "<tr>";
foreach (array_keys($dates[$firstDate]) as $classLetter) {
if ($j == 0) {
echo "<th></th>";
}
$j++;
echo "<th class='class-header'>{$classLetter}</th>";
}
echo "</tr>";
foreach ($dates as $date => $classes) {
echo "<tr>";
if ($i == 0) {
echo "<td class='time_row'>{$date}</td>";
}
foreach ($classes as $classLetter => $availability) {
if ($availability >= 0) {
$className = $availability > 0 ? "green" : "red";
}
if ($availability == "." || $availability == "-") {
$className = "purple";
}
echo "<td class='number_row {$className}'>{$availability}</td>";
}
echo "</tr>";
}
$i++;
echo "</table>";
echo "</div>";
}
}
}
So what's the best way to handle this code? I think I am right in not allowing my view to handle the above code, but then where should I do it?
Any advice on the design is appreciated.

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;
}

PHP/MySQL Printing Duplicate Labels

Using an addon of FPDF, I am printing labels using PHP/MySQL (http://www.fpdf.de/downloads/addons/29/). I'd like to be able to have the user select how many labels to print. For example, if the query puts out 10 records and the user wants to print 3 labels for each record, it prints them all in one set. 1,1,1,2,2,2,3,3,3...etc. Any ideas?
<?php
require_once('auth.php');
require_once('../config.php');
require_once('../connect.php');
require('pdf/PDF_Label.php');
$sql="SELECT $tbl_members.lastname, $tbl_members.firstname,
$tbl_members.username, $tbl_items.username, $tbl_items.itemname
FROM $tbl_members, $tbl_items
WHERE $tbl_members.username = $tbl_items.username";
$result=mysql_query($sql);
if(mysql_num_rows($result) == 0){
echo "Your search criteria does not return any results, please try again.";
exit();
}
$pdf = new PDF_Label("5160");
$pdf->AddPage();
// Print labels
while($rows=mysql_fetch_array($result)){
$name = $rows['lastname'].', '.$rows['firstname';
$item= $rows['itemname'];
$text = sprintf(" * %s *\n %s\n", $name, $item);
$pdf->Add_Label($text);
}
$pdf->Output('labels.pdf', 'D');
?>
Assuming that a variable like $copies is an integer of how many copies they want made, I would make the following modification:
// Print labels
while( $row = mysql_fetch_array( $result ) ){
// Run Once for Each Result
$name = $row['lastname'].', '.$row['firstname'];
$item = $row['itemname'];
$text = sprintf(" * %s *\n %s\n", $name, $item);
if( isset( $copies ) ) {
// The Copies Variable exists
for( $i=0 ; $i<$copies ; $i++ ) {
// Run X times - Once for each Copy
$pdf->Add_Label($text);
}
} else {
// The Copies Variable does not exist - Assume 1 Copy
$pdf->Add_Label($text);
}
}
This should provide the required functionality.

Categories