How to make horizontal table phpexcel? - phpexcel

$objPHPExcel->getActiveSheet()->setCellValue('A1', "No");
$objPHPExcel->getActiveSheet()->setCellValue('B1', "Name");
$objPHPExcel->getActiveSheet()->setCellValue('C1', "Age");
$objPHPExcel->getActiveSheet()->setCellValue('D1', "Job");
$styleArray = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THICK,'color' => array('argb' => '808080'),),),);
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->applyFromArray($styleArray);
$sql="SELECT * FROM CUBA";
$query_c = mysqli_query($conn,$sql);
$n=2;
while($row_result=mysqli_fetch_assoc($query_c)){
$objPHPExcel->getActiveSheet()->setCellValue('A'.$n,$row_result['id']);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$n,$row_result['name']);
$objPHPExcel->getActiveSheet()->setCellValue('C'.$n,$row_result['age']);
$objPHPExcel->getActiveSheet()->setCellValue('D'.$n,$row_result['job']);
$n++;
}
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
this is code for the table that i've done i want to change it to horizontal.
the table from the coding
the table that i desire want
horizontal table

As you're using $n for the row number; make it the column instead, and store each data item in rows 1-4:
$n='B';
while($row_result=mysqli_fetch_assoc($query_c)){
$objPHPExcel->getActiveSheet()->setCellValue($n.'1',$row_result['id']);
$objPHPExcel->getActiveSheet()->setCellValue($n.'2',$row_result['name']);
$objPHPExcel->getActiveSheet()->setCellValue($n.'3',$row_result['age']);
$objPHPExcel->getActiveSheet()->setCellValue($n.'4',$row_result['job']);
$n++;
}

Related

Cakephp 3: Collections getting to middle array entities

I'm trying to build a view that shows the most recent (now four but eventually five) years of data in a chart. I'm able to pull the data successfully in a variable the shows the most recent 4 years(I don't have the fifth year in the database yet). In order to break it down for the view and add some calculations on associated arrays, I have created a collection. I can get to the first and last array entity but can not figure out how to break out the middle two arrays.
public function viewAsuFiveYear()
{
$asuFiveYearEnrollments = $this->Enrollments->find('all', [
'contain' => ['Azinstitutions', 'FallFtes', 'FallHeadcounts', 'ProjectedEnrollments',
'FallHeadcounts.Locations', 'FallHeadcounts.StudentTypes', 'FallHeadcounts.ResidentStatuses', 'FallHeadcounts.Campuses',
'FallFtes.Locations', 'FallFtes.StudentTypes', 'FallFtes.ResidentStatuses', 'FallFtes.Campuses']
], ['limit' => 5])->where(['azinstitution_id' => 1])->order(['enrollment_year' => 'DESC']);
$collection = new Collection($asuFiveYearEnrollments);
$yearone = $collection->first();
$yearTwo = $collection->take(1, 1);
$yearFour = $collection->last();
$collection1HC = new Collection($yearone->fall_headcounts);
$onCampusesHc1 = $collection1HC->match(['location_id' => 1 ])->match(['campus_id' => NULL]);
$collection4HC = new Collection($yearFour->fall_headcounts);
$onCampusesHc4 = $collection4HC->match(['location_id' => 1 ])->match(['campus_id' => NULL]);
$this->set(compact('asuFiveYearEnrollments', 'azinstitutions', 'yearone', 'yearTwo', 'yearFour', 'onCampusesHc1', 'onCampusesHc4'));
}
I tried ->take (one array, second position) but it times out with that. Not sure what filter I can use to get to the 2nd or 3rd entity array.
I believe I've figured it out. May not be the best answer but it works. for the second year I skipped the 1st array and grabbed the first array in what was left.
and the same with the third year.
$yearTwo = $collection->skip(1)->first();
$yearThree = $collection->skip(2)->first();

How to Group By on Columns in datatable in Linq

var res3 = dtPriorityMatrix.AsEnumerable()
.GroupBy(hour => hour.Field<int>("Hour"))
.OrderBy(item => item.Key)
.Select(item => new { Hour = item.Key });
I have a data table with 5 columns and around 200+ rows of data. One has hours (0-23) and others are Priority 1, Priority 2 and so on till Priority 4. I need to extract number of items of each priority for every hour. I need help with the Linq query as it is not my strong field. Thanks
You have to group by both columns. something like this
var query = source.GroupBy(x => new { x.Column1, x.Column2 });
so your code will be
var res3 = dtPriorityMatrix.AsEnumerable()
.GroupBy(hour =>new { hour= hour.Field<int>("Hour"), priority=hour.Field<int>("Priority")} )
.Select(item => new {count=item.count(), Hour = item.Key.hour, priority = item.Key.priority});\
edit
Reply to your comment:
when you have your results in a list, you can write it in anyway that you want.
the out put of the query is a list that contains hour, priority and count.
if you want it in 3 lines of string
string hLine="";
string pLine="";
string countLine="";
foreach(var item in res3)
{
hLine+= item.hour+" ";
pLine+= item.prioriy+" ";
countLine+= item.count+" ";
}
if you want to have them in a table or anything, use the same approach for filling your tables items

How can I set column values to GridView Columns?

I have csv file like this:
I need to show this csv file with gridview. But I must change format like this:
I must select distinct just date and mount columns and use date values on gridview columns.
How can I use values of csv file for Gridview columns?
Assuming that reading the CSV file is not an issue and you have already something like a List<ClassName>, DataTable or List<string[]>. I'm presuming that it's a List<String[]> where the first "column" is Date, the second Mount and the last % in my following approach.
You need real DateTimes and ints to be able to sum percents by date:
var formatProvider = new CultureInfo("de-DE"); // seems to be the correct format
var mountGroups = listOfStringArray
.Select(arr => new
{
Date = DateTime.Parse(arr[0].Trim(), formatProvider).Date,
Mount = arr[1].Trim(),
Percent = int.Parse(arr[2].Trim())
})
.GroupBy(x => x.Mount);
Now you have grouped by Mount, you just need to sum the percents for every day. You can use a DataTable as datasource for the GridView. Here's code that creates the table with the dynamic columns for every day:
var dataSource = new DataTable();
dataSource.Columns.Add("Mount");
var lastWeekColumns = Enumerable.Range(0, 7)
.Select(d => new DataColumn(DateTime.Today.AddDays(-6 + d).ToShortDateString(), typeof(int)))
.ToArray();
dataSource.Columns.AddRange(lastWeekColumns);
Following loop executes the LINQ query and fills the table:
foreach(var grp in mountGroups)
{
DataRow row = dataSource.Rows.Add();
row.SetField("Mount", grp.Key); // because: GroupBy(x => x.Mount);
foreach(DataColumn dayCol in lastWeekColumns)
{
DateTime day = DateTime.Parse(dayCol.ColumnName, formatProvider);
int sumPercent = grp.Where(x => x.Date == day)
.Select(x => x.Percent)
.DefaultIfEmpty(0) // fallback value for missing days
.Sum();
row.SetField(dayCol, sumPercent);
}
}
Now you just need to use it as datasource (AuthoGenerateColumns set to true)
grid.DataSource = dataSource;
grid.DataBind();

Telerik Extensions for ASP.NET MVC - GRID - randomly sorted items inside group in Chrome when GridOperationMode.Client

Data source contains many records, but each 12 records represent 12 characteristic of 1 entity sorted in fixed order. Then rows are grouped by 3 columns (by 'AccountName', 'OportunityName' and 'OpportunityId'), and the group on deepest level contains those 12 characteristic. All worked OK when 'GridOperationMode.Server' was used:
But to increase performance we decided to change operation mode to client - 'GridOperationMode.Client'. After that performance became better, but those 12 characteristic lost they sorting in Chrome - for each group they are rendered in random order. I checked the issue in IE and FF - and found that they don't have such a problem. Any ideas how to fix the wrong order in chrome?
Wrong order in Chrome when GridOperationMode.Client is used
JS (shortened) - binds grid:
function populateForecastClosedGrid(controllerActionUrl) {
var gridForecastClosed = $("#gridFORECASTREPORT").data("tGrid");
var accountId = $('#accountsFilterCombo').data('tComboBox').value();
gridForecastClosed.ajax.selectUrl = controllerActionUrl + '?checkDate=' + new Date().formatMMDDYYYY() + '&accountId=' + accountId;
gridForecastClosed.showBusy();
$.post(gridForecastClosed.ajax.selectUrl, function (data) {
gridForecastClosed.dataSource.data([]);;
gridForecastClosed.dataBind(data);
});
}
Grid (shortened):
#(Html.Telerik().Grid()
.Name("gridFORECASTREPORT")
.Columns(columns => { ... }
.DataKeys(keys => keys.Add(c => c.OpportunityId))
.DataBinding(dataBinding => dataBinding.Ajax().OperationMode(GridOperationMode.Client))
.Groupable(grouping => grouping.Groups(groups =>
{
groups.Add(c => c.AccountName);
groups.Add(c => c.OpportunityName);
groups.Add(c => c.OpportunityId);
}).Visible(false))
.EnableCustomBinding(true)
.Pageable(p => p.PageSize(396)))
After a lot of researching I decided to implement sorting by myself using JS.
Works fast for page size equals 396 my grid uses, of course can be made faster. Each from those linked 12 items already has a field SortOrder with correct order inside this 12-items group. Quick and dirty, enjoy! If you know better solution please share. So far marked as answered. Really working solution, approved by my TL as no other ways found, can be adapted to any other grid.
function onGridForecastClosedDataBound() {
var grid = $(this).data('tGrid');
// Request came to increase Forecast (Closed) grid performance. The only way (w/o touching SQL)
// I found is to change grid operation mode from Server to GridOperationMode.Client (~50% increase).
// But Telerik Grid + Chrome (OK on IE, FF) has a problem - wrong sorted items inside group
// when grouping is performed on client side. This is a quick and dirty workaround for this
// particular grid - to perform "sorting" manually using JS.
// IMPORTANT! Pay attention, that if you change number of rows per
// opportunity (currently 12) then the grid will be broken w/o changing the code below.
if ('#Request.Browser.Browser' == 'Chrome') {
var numberOfRowsPerOpportunity = 12;
var rows = grid.$tbody.find('tr');
var rowsSorted = [];
while (rows.length > 0) {
var partGroups = rows.splice(0, rows.slice(0, grid.groups.length).filter('.t-grouping-row').length);
var partRows = rows.splice(0, numberOfRowsPerOpportunity);
partRows.sort(function (a, b) {
var sortOrderA = parseInt($(a).find('td.sort-order').text());
var sortOrderB = parseInt($(b).find('td.sort-order').text());
return sortOrderA - sortOrderB;
});
$.each(partRows, function (index, item) {
$(item).removeClass('t-alt');
if (index % 2 != 0) $(item).addClass('t-alt');
});
$.merge(rowsSorted, partGroups);
$.merge(rowsSorted, partRows);
}
rows.remove();
grid.$tbody.append(rowsSorted);
}
grid.hideBusy();
}
function populateForecastClosedGrid(controllerActionUrl) {
var gridForecastClosed = $("#gridFORECASTREPORT").data("tGrid");
var accountId = $('#accountsFilterCombo').data('tComboBox').value();
gridForecastClosed.ajax.selectUrl = controllerActionUrl + '?checkDate=' + new Date().formatMMDDYYYY() + '&accountId=' + accountId;
gridForecastClosed.showBusy();
gridForecastClosed.dataSource.data([]);
gridForecastClosed.ajaxRequest();
}
Grid (shortened):
#(Html.Telerik().Grid<mForecastReport>()
.Name("gridFORECASTREPORT")
.DataKeys(keys => keys.Add(c => c.OpportunityId))
.ClientEvents(e => e.OnDataBound("onGridForecastClosedDataBound"))
.DataBinding(dataBinding => dataBinding.Ajax().OperationMode(GridOperationMode.Client))
.Columns(columns => {
...
columns.Bound(c => c.SortOrder).Hidden(true).HtmlAttributes(new { #class = "sort-order" });
}
.Groupable(grouping => grouping.Groups(groups =>
{
groups.Add(c => c.AccountName);
groups.Add(c => c.OpportunityName);
groups.Add(c => c.OpportunityId);
}).Visible(false))
.Pageable(p => p.PageSize(396)))

server timeout on Dynamo DB query operation to get items from a table

I have an array of ids (eventids) which can be million or billion ids inside the table. I am using a for loop to go through each id and retrieve an item from a dynamo db table using the query operation in PHP. However, because the query operation goes over a large amount of info in my table, it takes too long the query operation to do its work. So, in this case I don't get any result because I get a time out. The following code tries to do this operation, which is failing for large amounts of info. I am wondering if you have any recommendation or suggestions on how to make the query operation faster and doable for large amounts of ids inside the $sfweventarrayRDS array?
for ($j = 0 ; $j < count($sfweventarrayRDS) ; $j++){
$keyconditions = array(
"eventid" => array(
"ComparisonOperator" => ComparisonOperator::EQ,
"AttributeValueList" => array(
array(Type::NUMBER => $sfweventarrayRDS[$j]["eventid"])
)
)
);
$sfweventarrayDynamo = Dynamo::getItems("eventlocation",$keyconditions,$limit);
if (count($sfweventarrayDynamo) > 0){
$timediffepoch = $sfweventarrayDynamo[0]["edatecreated"]["N"] - $sfweventarrayRDS[$j]["edatecreated"];
$timediffstandard = new DateTime("#$timediffepoch");
if ($timediffstandard->format('i') >= 5){
$starttimeepoch = $sfweventarrayRDS[$j]["edatecreated"];
$endtimeepoch = $sfweventarrayDynamo[0]["edatecreated"]["N"];
$starttimestandard = new DateTime("#$starttimeepoch");
$endtimestandard = new DateTime("#$endtimeepoch");
$each_event = array("eventid" => $sfweventarrayDynamo[0]["eventid"]["N"],
"organizationid" => $sfweventarrayRDS[$j]["organizationid"],
"userid" => $sfweventarrayDynamo[0]["userid"]["N"],
"starttime" => $starttimestandard->format('Y-m-d H:i:s'),
"endtime" => $endtimestandard->format('Y-m-d H:i:s'),
"location" => $sfweventarrayRDS[$j]["location"],
"startlatitude" => $sfweventarrayRDS[$j]["latitude"],
"startlongitude" => $sfweventarrayRDS[$j]["longitude"],
"endlatitude" => $sfweventarrayDynamo[0]["latitude"]["N"],
"endlongitude" => $sfweventarrayDynamo[0]["longitude"]["N"]);
array_push($safewalkeventsDynamo, $each_event);
}
}
}
There can be two possible solutions that can improve your query operation:
Use batch get: If you already know event IDs and want to query the db to get more information, then batch get would be ideal. You create a chunk of 100 IDs (max allowed) and call DynamoDB to get information in one go. Repeat until you get all the IDs. Here is the documentation link.
You can increase your tables' read capacity according to your needs. (This will result in paying more money for dynamoDB.)

Resources