Creating spreadsheet with PHPExcel - phpexcel

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');
?>

Related

image.filter is not a function in google earth engine

As a newbie to the google earth engine, I have been trying something (https://code.earthengine.google.com/6f45059a59b75757c88ce2d3869fc9fd) following a NASA tutorial (https://www.youtube.com/watch?v=JFvxudueT_k&ab_channel=NASAVideo). My last line (line 60) shows image.filter is not a function, while the one in the tutorial (line 34) is working. I am not sure what happened and how to sort this out?
//creating a new variable 'image' from the L8 collection data imported
var image = ee.Image (L8_tier1 //the details in the data will represent that the band resolution is 30m
//the details in the data will represent that the band resolution is 30m
//.filterDate ("2019-07-01","2021-10-03") //for a specific date range. maybe good to remove it for the function.
//the details in the data will represent that the band resolution is 30m
//the details in the data will represent that the band resolution is 30m
//.filterDate ("2019-07-01","2021-10-03") //for a specific date range. maybe good to remove it for the function.
.filterBounds (ROI) //for the region of interest we are interested in
//.sort ("COLUD_COVER") //for sorting the data between the range with a cloud cover, the metadata property we are interested in. Other way to do this is using the function below.
//.first() //this will make the image choose the first image with the least amount of cloud cover for the area. Other way to do this is using the function below.
);
//print ("Hague and Rotterdam", image); //printing the image in the console
//console on the right hand side will explain everything from the data
//id will show the image deatils and date of the image, for this case 29th July 2019
//under the properties tab cloud cover can be found, this is the least we can get for this area during this period
// //vizualisation of the data in the map with true color rendering
// var trueColour = {
// bands:["SR_B4","SR_B3","SR_B2"],
// min: 5000,
// max: 12000
// };
// Map.centerObject (ROI, 12); //for the centering the area in the center of the map with required zoom level
// Map.addLayer (image, trueColour, "Hague and Rotterdam"); //for adding the image with the variable of bands we made and naming the image
//Alternate way
//Function to cloud mask from the qa_pixel band of Landsat 8 SR data. In this case bits 3 and 4 are clouds and cloud shadow respectively. This can be different for different image sets.
function maskL8sr(image) {
var cloudsBitMask = 1 << 3; //remember to check this with the source
var cloudshadowBitMask = 1 << 4; //remember to check this with the source
var qa = image.select ('qa_pixel'); //creating the new variable from the band of the source image
var mask = qa.bitwiseAnd(cloudsBitMask).eq(0) //making the cloud equal to zero to mask them out
.and(qa.bitwiseAnd(cloudshadowBitMask).eq(0)); //making the cloud shadow equal to zero to mask them out
return image.updateMask(mask).divide(10000)
.select("SR_B[0-9]*")
.copyProperties(image, ["system:time_start"]);
}
// print ("Hague and Rotterdam", image);// look into the console now. How many images the code have downloaded!!!
//filtering imagery for 2015 to 2021 summer date ranges
//creating joint filter and applying to image collection
var sum21 = ee.Filter.date ('2021-06-01','2021-09-30');
var sum20 = ee.Filter.date ('2020-06-01','2020-09-30');
var sum19 = ee.Filter.date ('2019-06-01','2019-09-30');
var sum18 = ee.Filter.date ('2018-06-01','2018-09-30');
var sum17 = ee.Filter.date ('2017-06-01','2017-09-30');
var sum16 = ee.Filter.date ('2016-06-01','2016-09-30');
var sum15 = ee.Filter.date ('2015-06-01','2015-09-30');
var SumFilter = ee.Filter.or(sum21, sum20, sum19, sum18, sum17, sum16, sum15);
var allsum = image.filter(SumFilter);
Filtering is an operation you can do on ImageCollections, not individual Images, because all filtering does is choose a subset of the images. Then, in your script, you have (with the comments removed):
var image = ee.Image (L8_tier1
.filterBounds (ROI)
);
The result of l8_tier1.filterBounds(ROI) is indeed an ImageCollection. But in this case, you have told the Earth Engine client that it should be treated as an Image, and it believed you. So, then, the last line
var allsum = image.filter(SumFilter);
fails with the error you saw because there is no filter() on ee.Image.
The script will successfully run if you change ee.Image(...) to ee.ImageCollection(...), or even better, remove the cast because it's not necessary — that is,
var image = L8_tier1.filterBounds(ROI);
You should probably also change the name of var image too, since it is confusing to call an ImageCollection by the name image. Naming things accurately helps avoid mistakes, while you are working on the code and also when others try to read it or build on it.

PHPExcel Get data fromDatabase and put value into cells

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!

Google Maps Markers - lat, long, size and color from Excel

I am trying to reproduce something that I have created in Google Earth/KML but have problems in Google Maps due to my inexperience with JS.
I want to load around 1000 markers using lat, long, size and color data from XLS.
I have seen an example of how to control market position and size using data from a JSON source,
I have also seen an example of an import from XLS to a JS array.
In the XLS file the data is in columns: Lat, Long, Size, Color and Label. The color can be expressed in CSS. The label would be the basis of a tooltip.
Any suggestions welcome.
Many thanks
Steve
I have done this several times. There are a few options...
Have a look at Google Fusion Tables - these are really easy to use and lightning fast - able to deal with 500,000 points.
For 1,000 points, I would export the Excel data to a CSV file, then convert the CSV to a Javacript array, and embed the array and some Javascript into your webpage. I am providing a Perl script that will convert the CSV you get out of Excel into a Javascript array - it may not be perfect but you will get the idea. Then I am providing some Javascript that creates the markers, which may also not be perfect, but you will get the idea.
So, this converts a CSV file into Javascript array:
#!/usr/bin/perl
use strict;
use warnings;
my $printcomma=0;
print "var Points = new Array(\n";
while (<>) {
# Trim end of line character
chomp;
my $line = $_;
# Define variables to hold each CSV field
my ($lat,$lon,$size,$color,$label) = split (',',$line);
print ",\n" if $printcomma;
print "{lat:'$lat',lon:'$lon',size:'$size',color:'$color',label:'$label'}";
$printcomma = 1;
END
}
print ");\n";
You save it as "csv2js", then you go to a Terminal and type:
chmod +x csv2js
./csv2js < yourCSVfile > points.js
Assuming your CSV file looks something like this:
53.1,0.002,100,255,Some label
52.7,0.011,1000,200,Another label
55.89,-0.78,10000,128,Yet another label
it will create a file that looks something like this:
var Points = new Array(
{lat:'53.1',lon:'0.002',size:'100',color:'255',label:'Some label'},
{lat:'52.7',lon:'0.011',size:'1000',color:'200',label:'Another label'},
{lat:'55.89',lon:'-0.78',size:'10000',color:'128',label:'Yet another label'});
Then you inclue the file created above (points.js) into the top of the following file and use that as the basis of your HTML webpage:
<HTML>
<head>
<!-- Pull in Javascript version of Excel CSV -->
<script src="points.js"></script>
<!-- A bunch of your own stuff -->
<script type="text/javascript">
////////////////////////////////////////////////////////////////////////////////
// This function is called dynamically to build the Infowindow as it pops up as
// a result of the user clicking a pin on the map.
////////////////////////////////////////////////////////////////////////////////
function DeriveInfowindowContent(i){
// Build the wording for the pop-up Infowindow, one piece at a time;
var t1 = "<h4>" + Points[i].label + "</h4>";
return t1;
}
////////////////////////////////////////////////////////////////////////////////
// Function called when webpage first loads
////////////////////////////////////////////////////////////////////////////////
function initialize() {
////////////////////////////////////////////////////////////////////////////////
// Next line sets the latitude/longitude of map centre at startup. Use tools at
// http://www.getlatlon.com to find a nice, new map centre's coordinates.
////////////////////////////////////////////////////////////////////////////////
var myMapCentre = new google.maps.LatLng(51.50,-0.135);
////////////////////////////////////////////////////////////////////////////////
// "zoom" sets the zoom (or scale) of the map
// Use any value between 0-20, 12 seems about right to me.
// Smaller numbers mean you see a larger area of ground in your browser.
////////////////////////////////////////////////////////////////////////////////
var myOptions = {
zoom: 12,
center: myMapCentre,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
gmap = map; // Store in global var gmap
// Just use one Infowindow and set its content each time before use, this
// saves memory and means old infowindow closes when user opens a new one.
var Infowindow = new google.maps.InfoWindow();
// Go through plotting all points on map
for(var i=0;i<Points.length;i++){
Points[i].LatLon = new google.maps.LatLng(Points[i].lat,Points[i].lon);
Points[i].Marker = new google.maps.Marker({position:Points[i].LatLon,map:map});
Points[i].Marker.index = i;
google.maps.event.addListener(Points[i].Marker, 'click', function() {
var s=DeriveInfowindowContent(this.index);
Infowindow.setContent(s);
Infowindow.open(map,this);});
}
}
</script>
</head>
<body onload="initialize()">
Note that this code doesn't do anything with the "color" or the "size" parameters in your Excel spreadsheet, but I guess you can work those bits out yourself now you have a basic structure.
UPDATE: Since doing this I have found a nice Javascript library that will parse your Excel-produced CSV file into an array for you, which means you won't need my Perl above. See Evan's answer to this question.

create the new sheet in phpexcel and set the cell value

I am trying to use phpexcel to set the template purchase order .
I have set column 25 to 43 is for details of purchase item. It mean it will retrieve data from database and set all the value in column 25 to 43 .As addition ,these column only can fit for 6 item. I am facing problem when the purchase item is too many and cannot fit into the column that i had set.
My code is work,but it is too long. Anyone have a better solution?
after create both sheet,i have to set the other cellvalue one by one in both sheet.It make the code become very long.Appreciate for who can help.
$objPHPExcel->setActiveSheetIndex(0);
$result = mysql_query("SELECT purchasematerial.PONum,purchasematerial.QuoNum,purchasematerial.date, material.product,purchasematerial.description,purchasematerial.unit_price,purchasematerial.UOM,purchasematerial.qua ntity ,purchasematerial.amount FROM purchasematerial INNER JOIN material ON purchasematerial.product=material.id where PONum='$PONum'");
$col=25;
$num=1;
while($row = mysql_fetch_array($result)){
if($col<43){
$objPHPExcel->getActiveSheet()->setCellValue('AA11', $row['PONum']);
$date = new DateTime($row['date']);
$objPHPExcel->getActiveSheet()->setCellValue('AA12', $date->format('d-M-y'));
$objPHPExcel->getActiveSheet()->setCellValue('I45', '=AA12+7');
$QuoNum=$row['QuoNum'];
if ($QuoNum=='' || $QuoNum== null)
$objPHPExcel->getActiveSheet()->setCellValue('I47', "N/A");
else
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum']);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$col, $num);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$col, $row['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$col, $row['description']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$col, $row['unit_price']);
$objPHPExcel->getActiveSheet()->setCellValue('V'.$col, $row['UOM']);
$objPHPExcel->getActiveSheet()->SetCellValue('Y'.$col, $row['quantity']);
$objPHPExcel->getActiveSheet()->SetCellValue('AB'.$col, $row['amount']);
$col=$col+3;
$num++;
}
else{
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);
$col=25;
$objPHPExcel->getActiveSheet()->setCellValue('AA11', $row['PONum']);
$date = new DateTime($row['date']);
$objPHPExcel->getActiveSheet()->setCellValue('AA12', $date->format('d-M-y'));
$objPHPExcel->getActiveSheet()->setCellValue('I45', '=AA12+7');
$QuoNum=$row['QuoNum'];
if ($QuoNum=='' || $QuoNum== null)
$objPHPExcel->getActiveSheet()->setCellValue('I47', "N/A");
else
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum']);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$col, $num);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$col, $row['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$col, $row['description']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$col, $row['unit_price']);
$objPHPExcel->getActiveSheet()->setCellValue('V'.$col, $row['UOM']);
$objPHPExcel->getActiveSheet()->SetCellValue('Y'.$col, $row['quantity']);
$objPHPExcel->getActiveSheet()->SetCellValue('AB'.$col, $row['amount']);
$col=$col+3;
$num++;
}
}
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->getStyle('I45')->getNumberFormat()- >setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15);
$objPHPExcel->getActiveSheet()->setCellValue('AC1', 'WEEKNUM(I45)');
$objPHPExcel->getActiveSheet()->setCellValue('Q44', 'TOTAL');
$objPHPExcel->getActiveSheet()->SetCellValue('Y44','RM');
$objPHPExcel->getActiveSheet()->SetCellValue('AB44', '=SUM(AB25:AB43)');
$objPHPExcel->getActiveSheet()->getStyle('Q44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('Y44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('AA44')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->getStyle('I45')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15);
$objPHPExcel->getActiveSheet()->setCellValue('AC1', 'WEEKNUM(I45)');
$objPHPExcel->getActiveSheet()->setCellValue('Q44', 'TOTAL');
$objPHPExcel->getActiveSheet()->SetCellValue('Y44','RM');
$objPHPExcel->getActiveSheet()->SetCellValue('AB44', '=SUM(AB25:AB43)');
$objPHPExcel->getActiveSheet()->getStyle('Q44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('Y44')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('AA44')->getFont()->setBold(true);
One way might be to use the fluent interface.
Instead of
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum']);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$col, $num);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$col, $row['product']);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$col, $row['description']);
$objPHPExcel->getActiveSheet()->SetCellValue('S'.$col, $row['unit_price']);
$objPHPExcel->getActiveSheet()->setCellValue('V'.$col, $row['UOM']);
$objPHPExcel->getActiveSheet()->SetCellValue('Y'.$col, $row['quantity']);
$objPHPExcel->getActiveSheet()->SetCellValue('AB'.$col, $row['amount']);
do
$objPHPExcel->getActiveSheet()->setCellValue('I47', $row['QuoNum'])
->setCellValue('A'.$col, $num)
->setCellValue('B'.$col, $row['product'])
->SetCellValue('J'.$col, $row['description'])
->SetCellValue('S'.$col, $row['unit_price'])
->setCellValue('V'.$col, $row['UOM'])
->SetCellValue('Y'.$col, $row['quantity'])
->SetCellValue('AB'.$col, $row['amount']);
so that you're not constantly calling $objPHPExcel->getActiveSheet()
For setting the second sheet, as the cells are identical to the first; you could create a function to set the cell values and just call that function twice (basic PHP 101). Alternatively, you could set the cells for the first sheet, then clone that sheet and set the clone as the second sheet.

PHPexcel - How can I load an excel file from url

I'm having the following code that I'm using to load, read, write and download an excel file.
//include PHPExcel library
require_once "Classes/PHPExcel/IOFactory.php";
//load Excel template file
$objTpl = PHPExcel_IOFactory::load("excel.xls");
$objTpl->setActiveSheetIndex(0); //set first sheet as active
$objTpl->getActiveSheet()->setCellValue('C2', date('Y-m-d')); //set C1 to current date
$objTpl->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //C1 is right-justified
$strData = $objTpl->getActiveSheet()->getCell('C3')->getValue();
$strData .= $objTpl->getActiveSheet()->getCell('C4')->getValue();
$objTpl->getActiveSheet()->setCellValue('C3', 'It\'s working');
$objTpl->getActiveSheet()->setCellValue('C4', 'Dynamic excel read and writing');
$objTpl->getActiveSheet()->setCellValue('C6', 'Data read: C3 = '.substr($strData,0,1).' and C4 = '.substr($strData,1,1));
$objTpl->getActiveSheet()->getStyle('C4')->getAlignment()->setWrapText(true); //set wrapped for some long text message
$objTpl->getActiveSheet()->getColumnDimension('C')->setWidth(40); //set column C width
$objTpl->getActiveSheet()->getRowDimension('4')->setRowHeight(120); //set row 4 height
$objTpl->getActiveSheet()->getStyle('A4:C4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP); //A4 until C4 is vertically top-aligned
//prepare download
$filename=mt_rand(1,100000).'.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5'); //downloadable file is in Excel 2003 format (.xls)
$objWriter->save('php://output'); //send it to user, of course you can save it to disk also!
My problem is that I want to load the excel file from a different source(url,stream), not from the local directory
Simply save the file to your server and then read it.
file_put_contents('excel.xls',
file_get_contents('https://www.myweburl.com/spreadsheets.xls')
);
$objTpl = PHPExcel_IOFactory::load("excel.xls");

Resources