How to increase columns in PHP excel - php

I am making dynamic columns and my columns are 1000+ , can anybody guide me how to increase columns in PHPexcel. How can I increase my column length while creating dynamic columns? or Is there any other way For your reference I am showing my code below:
private function _buildExcellTableData(ExportExcel $excel)
{
$excel->row++;
$excel->row++;
$sheet = $excel->excel->getActiveSheet();
$sheet->setCellValue('D1', 'Role Requirement Report');
$header1 = $sheet->mergeCells('D1:G1')->getStyle('D1');
$header1->getFont()->setSize(18)->setBold(true);
$header1->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('E6E6E6');
$alpha = 'B';
$countCells = count($this->data['roles']);
$header = $sheet->getStyle('A'.$excel->row);
$header->getFont()->setBold(true);
$header->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('E6E6E6');
$sheet->getStyle('A'.$excel->row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
$sheet->getColumnDimension('A')->setAutoSize(TRUE);
$sheet->setCellValue('A'.$excel->row, 'Roles/Requirements');
$rolesIds = array_map(create_function('$o', 'return $o->id;'), $this->data['roles']);
foreach($this->data['roles'] as $key=>$value)
{
for ($i = 0; $i < $countCells; $i++)
{
$sheet->getColumnDimension($alpha)->setAutoSize(TRUE);
$sheet->setCellValue($alpha.'6',$value->title);
}
$alpha++;
}
$row_start = $excel->row;
foreach ($this->data['rolesrequirement'] as $key=>$row)
{
$excel->row++;
$sheet->setCellValue('A' . $excel->row, $row->title);
$roleCheck = array_map('trim', explode(',', $row->roleid));
$alpha = 'B';
for ($i = 0; $i < $countCells; $i++)
{
$value = (in_array($rolesIds[$i], $roleCheck)) ? 'x' : '';
$sheet->getStyle($alpha.$excel->row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->setCellValue($alpha.$excel->row, $value);
$alpha++;
}
}
$row_style = $sheet->getStyle('A'.$row_start);
$row_style->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
}
Thanks in advance!

Related

How to Generate a Dynamic Text in a html List

I need to generate a dynamic text in accordance with the number of data that comes from the database.
In a html List, I need to display the following text as example:
GROUP A
GROUP B
GROUP C
If the amount of records coming from the DB is only 1000, then only one item list is displayed. 1000 records equals 1 Item list.
The text must be dynamically changed as described above.
Each text in the list is displayed for 1000 records.
The code below statically displays 11 items
I've made a few tries on the code below but still to no avail.
This code is working, but it display only the static text.
$return .= "<div id='test_id'><ul>";
// $qty = 10424 / $limit = 1000
// $tabs = $qty / $limit = 10,424
$tabs = $qty/$limit;
for ($i=0; $i < $tabs ; $i++)
{
$start = $i * $limit + 1;
$end = ($i + 1) * $limit;
$color = 'classpA';
$message = '<small>GROUP A</small>';
if ($i < $tab_selected) {
$color = 'classB';
$message = 'RESERVED';
}
$active = $i == $tab_selected ? "active" : "";
$return .= "<li class='tab {$color} {$active}' tab-id='#tab-".$i."'>
<span class='available {$color}_text'><small>{$message}</small></span>
<a href='#' class='{$color}_text'>".$start." - ".min($end,$qty)."</a></li>";
}
$return .= "</ul></div>";
And this is that logic that i`m trying to apply
$qty = 18424;
$limit = 1000;
$tabs = ($qty / $limit);
$group = $tabs / $limit;
$alphabet = 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');
for($i = 0; $i < $group; $i++) {
echo "Group {$alphabet[$i]}".'<br>';
}
echo 'Qtd Group= '.$group.' Value Var Tabs= '.$tabs;
https://www.tehplayground.com/zyVzmaeYnTyyA4S9
How can I make the magic happen?
Your logic is fine, just the limit to the for loop seems to be miscalculated.
Right now, for the variable group = (qty/limit)/limit, you have an extra division by limit here.
Whatever your need maybe for that division, you can simply use the value of tabs in your for loop condition, or assign it to another temporary variable its up to you.
for($i = 0; $i < $tabs; $i++) {
echo "Group {$alphabet[$i]}".'<br>';
}
Cheers!
Maybe this could helps you
<?php
//$tabs = ($qty / $limit);
//$group = $tabs / $limit;
$alphabet = 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');
$return = 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');
$a = array_chunk($return, 3);
//$a = array_chunk($return, $limit);
$key = 0;
$group = array();
$r = count($a);
foreach($alphabet as $v)
{
if($key < $r)
{
if(!isset($group[$v]))
{
$group[$v] = array();
}
$group[$v] = $a[$key];
$key++;
}
}
print_r($group);
Here
https://www.tehplayground.com/bfmZOubIMdmBcjhu

Index in for loop not returning last index

I have an image gallery and each is saved by index.. gallery1: /image here.. gallery2: / image here.. etc..
I'm using an index with multiple for loops to return the images and by column because it's either Masonry or rectangular. I am getting the return fine except for the very last index.
private function rectangle($items, $columns, $contents = array()) {
$thumbs = array('talent_thumbnail','360x207');
$arr = array();
$col = round(count($items) / $columns);
$perCol = floor(count($items) / $columns);
$extra = count($items) % $columns;
$ind = 1;
$length = count($items);
$arr = array();
for($i = 0; $i < $columns && $ind < $length; $i++) {
$temp = array();
for($j = 0; $j < $perCol; $j++) {
$obj = new JObject();
$obj->image = $items['gallery' . $ind]['photo'];
$obj->alt_text = $items['gallery'. $ind]['alt_text'];
$temp[] = $obj;
$ind++;
}
if ($extra > 0) {
$obj = new JObject();
$obj->image = $items['gallery'. $ind]['photo'];
$obj->alt_text = $items['gallery'. $ind]['alt_text'];
$temp[] = $obj;
$ind++;
$extra--;
}
$arr[] = $temp;
}
}
I know it can't be that hard but I'm not that good at it right yet.
Any help is so much welcome.
Thank You.
You set the variable $ind to 1, count the length of the array, and then initialize the for loop with the condition $ind < $length.
When $ind reaches the index needed to access the last item, the loop is not run again, since $ind is now equal to $length, not smaller.
You can fix this by changing the condition in your for-loop to "less or equal":
$i < $columns && $ind <= $length
This runs the loop once more when $ind has reached the last index.
Probably the problem is at this line:
$ind = 1;
In PHP non-associative arrays have the indexes starting to 0 instead of 1:
$arr = array('a', 'b', 'c');
print_r($arr);
// output:
Array ( [0] => a [1] => b [2] => c )
So, try to change that line in your code to:
$ind = 0;
Complete code:
private function rectangle($items, $columns, $contents = array()) {
$thumbs = array('talent_thumbnail','360x207');
$arr = array();
$col = round(count($items) / $columns);
$perCol = floor(count($items) / $columns);
$extra = count($items) % $columns;
$ind = 0;
$length = count($items);
$arr = array();
for($i = 0; $i < $columns && $ind < $length; $i++) {
$temp = array();
for($j = 0; $j < $perCol; $j++) {
$obj = new JObject();
$obj->image = $items['gallery' . $ind]['photo'];
$obj->alt_text = $items['gallery'. $ind]['alt_text'];
$temp[] = $obj;
$ind++;
}
if ($extra > 0) {
$obj = new JObject();
$obj->image = $items['gallery'. $ind]['photo'];
$obj->alt_text = $items['gallery'. $ind]['alt_text'];
$temp[] = $obj;
$ind++;
$extra--;
}
$arr[] = $temp;
}
}

Creating multi column and multi page pdfs with FPDF

I am trying to utilize the FPDF module with Laravel (crabbly/fpdf-laravel)
The need is to create a 1+ page 3-column documents.
In the essence, I have a list of pairs TERM:DESCRIPTION that I need to output one after another. I am struggling with the overall logic and I am not even sure if I am doing it the right way and wondering if there is a better solution to this (whoever is familiar with FPDF)
Get the list of Term:Description pairs ($glossary)
Separate each Description into lines that are below 75 characters in length
Count how many lines already in the column
Add lines to the coumn
Switch Page/Column when numbers of lines exceed the defined length of 51 lines per column
This is the code I came up with:
public function getCreatePDF($flascard_id) {
$flashcard = Flashcard::where('user_id', auth()->id())->findOrFail($flascard_id);
$glossary = Glossary::with('flashcarditem')
->whereHas('flashcarditem', function ($query) use ($flascard_id) {
$query->where('flashcard_id', '=', $flascard_id);
})
->get();
$pdf = app('FPDF');
$pdf->col = 0;
$pdf->AcceptPageBreak(false);
//My Loop Controls
$column = 0; //Control which column to add data
$columnLenght = 0; //monitor if we need to change the column
$maxLinesPerColumn = 51;
$wrapCharacters = 75; //do not exceed this char qty per line
$collectedDescription = ""; //stack Description here
$pdf->AddPage(['L', 'Letter']);
$pdf->SetFont('Arial', 'B');
$pdf->SetFontSize(18);
$mid_x = 135; // the middle of the "PDF screen", fixed by now.
$pdf->Text($mid_x - ($pdf->GetStringWidth('TITLE') / 2), 102, 'TITLE');
$pdf->AddPage(['L', 'Letter']);
$pdf->SetFontSize(7);
foreach ($glossary as $key => $g) {
$chunks = explode("\n", wordwrap(strip_tags($g->description), $wrapCharacters));
$actionCollect = 1;
$collectedDescription = "";
for ($i = 0; $i < count($chunks); $i++) {
if ($columnLenght > $maxLinesPerColumn && $column == 2) {
$column = 0;
$columnLenght = 1;
$pdf->AddPage(['L', 'Letter']);
$pdf->Footer("d");
$pdf->col = $column;
$x = 10 + $column * 95;
$pdf->SetLeftMargin($x);
$pdf->SetX($x);
$pdf->SetY(8);
$actionCollect = 0;
} else if ($columnLenght > $maxLinesPerColumn && $column < 2) {
$columnLenght = 1;
$column++;
$pdf->col = $column;
$x = 10 + $column * 95;
$pdf->SetLeftMargin($x);
$pdf->SetX($x);
$pdf->SetY(8);
$actionCollect = 0;
} else {
$columnLenght ++;
$actionCollect = 1;
}
if ($i == 0) {
$columnLenght ++;
$pdf->SetFont('Arial', 'B');
$term = html_entity_decode($g->term);
$pdf->MultiCell(90, 3, $term, 'R');
$pdf->Ln(0);
}
$collectedDescription.=strip_tags($chunks[$i]);
if (count($chunks) - 1 && $i == 0) {
$pdf->SetFont('Arial');
$pdf->MultiCell(90, 3, $collectedDescription, 'R');
$actionCollect = 0;
$collectedDescription = "";
} else {
$pdf->SetFont('Arial');
$pdf->MultiCell(90, 3, strip_tags($chunks[$i]), 'R');
$actionCollect = 0;
$collectedDescription = "";
}
}
$pdf->Ln(1);
}
}
My Desired state

PHP - How to create all possibility from a string

Here, there is a example string "XjYAKpR" .. how to create all new string possibility with that string ??
I've tried before
function containAllRots($s, $arr) {
$n = strlen($s);
$a = array();
for ($i = 0; $i < $n ; $i++) {
$rotated = rotate(str_split($s), $i);
$a[] = $rotated;
}
print_r($a);die();
if (array_diff($arr, $a)) {
return True;
}
else
{
return False;
}
}
I make 2 function rotate and generate
function rotate($l, $n) {
$b = $l[$n];
$sisa = array_values(array_diff($l, array($b)));
for ($i = 0; $i < count($sisa) ; $i++) {
$random[] = generate($sisa, $b);
}
print_r($random);die();
$hasil = $l[$n] . implode("",$random);
return $hasil;
}
function generate($sisa, $b) {
$string = implode("",$sisa);
$length = count($sisa);
$size = strlen($string);
$str = '';
for( $i = 0; $i < $length; $i++ ) {
$str .= $string[ rand( 0, $size - 1 ) ];
}
Here there is a pair of functions that lets you calculate a permutation set
(no repetitions are taken in account)
function extends_permutation($char, $perm) {
$result = [];
$times = count($perm);
for ($i=0; $i<$times; $i++) {
$temp = $perm;
array_splice($temp, $i, 0, $char);
array_push($result, $temp);
}
array_push($result, array_merge($perm, [$char]));
return $result;
}
function extends_set_of_permutations($char, $set) {
$step = [];
foreach ($set as $perm) {
$step = array_merge($step, extends_permutation($char, $perm));
}
return $step;
}
you can use them to generate the required set of permutations. Something like this:
$seed = "XjYAKpR";
// the first set of permutations contains only the
// possible permutation of a one char string (1)
$result_set = [[$seed[0]]];
$rest = str_split(substr($seed,1));
foreach($rest as $char) {
$result_set = extends_set_of_permutations($char, $result_set);
}
$result_set = array_map('implode', $result_set);
sort($result_set);
At the end of the execution you will have the 5040 permutations generated by your string in the result_set array (sorted in alphabetical order).
Add a char and you will have more than 40000 results.
The functions are quite naive in implementation and naming, both aspects can be improved.

Generate multiple coupon codes at once; separated by comma

I found this Stack Overflow post explaining how you can generate random coupon codes.
I'm looking into using that code and generate multiple coupons at once (e.g. 50), while separate them by a comma.
The output would be: COUPON-HMECN, COUPON-UYSNC, etc.
Code below and codepad example available.
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "COUPON-";
for ($i = 0; $i < 5; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
echo $res . ",";
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numCodesToGenerate = 5;
for ($n = 0; $n < $numCodesToGenerate; $n++)
{
$res = "COUPON-";
for ($i = 0; $i < 5; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
echo $res . ",";
}
Why not use uniqid()?
$coupon_str = '';
$seperator = '';
for($i = 0; $i < 50; $i++) {
$coupon_str .= $seperator . uniqid('COUPON-');
$seperator = ',';
}
echo $coupon_str;
Output:
COUPON-502373ac95dd2,COUPON-502373ac95de8,COUPON-502373ac95ded,....
Here is a much neater version (and faster) that does what you need:
function MakeCouponCode() {
$res = "COUPON-";
for($i = 0; $i < 5; ++$i)
$res .= chr(mt_rand(0, 1) == 0 ? mt_rand(65, 90) : mt_rand(48, 57));
return $res;
}
$coupons = array();
for($i = 0; $i < 5; ++$i)
$coupons[] = MakeCouponCode();
echo implode(', ', $coupons);
Output:
COUPON-D707Y, COUPON-4B37E, COUPON-3O397, COUPON-M799X, COUPON-24Q36
You can use the coupon code generator PHP class file to generate N number of coupons and its customizable, with various options of adding own mask with own prefix and suffix. The coupon codes are separated by comma. Simple PHP coupon code generator
Example:
coupon::generate(8); // J5BST6NQ

Categories