Not able to apply formula to the excel spreadsheet using phpexcel? - php

I am using PHPExcel in my php code to generate an excel report with a number to spreadsheets but i want to apply formula complete columns in those spreadsheets and i am using the following code but its just applying the same values to the complete column but i want the formula to run and give values depending on the each cell column G of my worksheet, and i want these resulting values in column Q.
Following is the complete code that i am using:
<?php
$dbhost= "localhost"; //your MySQL Server
$dbuser = "root"; //your MySQL User Name
$dbpass = "root"; //your MySQL Password
$dbname = "pyramid";
//your MySQL Database Name of which database to use this
$tablename = "peachtree"; //your MySQL Table Name which one you have to create excel file
// your mysql query here , we can edit this for your requirement
$tablename1 = "shipping";
$tablename2 = "embassies";
$tablename3 = "documentprocesses";
$tablename4 = "documentdetails";
$tablename5 = "documents";
$sql = "Select * from $tablename ";
$sql1= "Select * from $tablename1";
$sql2= "Select * from $tablename2";
$sql3= "Select filter1.docID,
filter1.salesOrderID,
IF(filter1.docSource='shipping', 'Shipping', 'Non-Shipping') AS 'Doc Type',
filter1.countryID,
DATE(filter1.docTimeStamp) AS 'Date Received',
IF(filter2.processStartDate IS NULL, 'OPEN',
DATE(filter2.processStartDate)) AS 'Date Shipped',
$tablename3.processCode,
$tablename3.destination,
$tablename3.processStartDate,
$tablename4.*,
filter1.docValue
FROM ( SELECT docID,
salesOrderID,
docSource,
docValue,
countryID,
docTimeStamp
FROM $tablename5
WHERE DATE(docTimeStamp) <= '2015-03-31' ) AS filter1
JOIN (
SELECT docID,
processStartDate
FROM $tablename3
WHERE processCode = 'SHPD'
AND( processStatus <> 'completed'
OR DATE(processStartDate) > '2015-03-31')
) AS filter2
ON filter1.docID = filter2.docID
LEFT JOIN (
SELECT *
FROM $tablename3
WHERE DATE(processStartDate) <= '2015-03-31'
AND processStartDate IS NOT NULL) AS $tablename3
ON $tablename3.docID = filter2.docID
LEFT JOIN $tablename4 ON $tablename4.docID = filter2.docID";
//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());
$result1 = #mysql_query($sql1,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$result2 = #mysql_query($sql2,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$result3 = #mysql_query($sql3,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
error_reporting(E_ALL);
set_time_limit(0);
ini_set('memory_limit','2500M');
require_once dirname(__FILE__) . '/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 = 0; $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=0; $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++;
}
$objPHPExcel->getActiveSheet()->setTitle('peachtree');
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(1);
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 0; $i < mysql_num_fields($result1); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result1,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result1))
{
$column = 'A';
for($j=0; $j<mysql_num_fields($result1);$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++;
}
$objPHPExcel->getActiveSheet()->setTitle('shipping');
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(2);
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 0; $i < mysql_num_fields($result2); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result2,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result2))
{
$column = 'A';
for($j=0; $j<mysql_num_fields($result2);$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++;
}
$objPHPExcel->getActiveSheet()->setTitle('embassies');
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex(3);
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 0; $i < mysql_num_fields($result3); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result3,$i));
$column++;
}
$column = 'Q';
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount,"SOS");
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result3))
{
$column = 'A';
for($j=0; $j<mysql_num_fields($result3);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
***$column = 'Q';
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount,'=IF(column="SOS",15,0)');
$rowCount++;***
}
$objPHPExcel->getActiveSheet()->setTitle('documentdata');
// 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');

Wading through your wall of code
=IF(column="SOS",15,0)
Doesn't look like a valid Excel formula to me. What is column? If it was an Excel named range, or a cell reference, then it would work; but as it stands it's nothing that would be valid in an Excel formula.
Your formula must be a valid Excel formula
EDIT
If you want to set a single cell to a value of 15 or 0 depending on whether any cell in column G contains the value "SOS", then an appropriate MS Excel formula for that would be
=IF(ISERROR(MATCH("SOS",G:G, 0)), 0, 15)
If you want to do this check on a row by row basis, then you'd set your formula to something like:
$objPHPExcel->getActiveSheet()
->setCellValue($column.$rowCount,'=IF(G'.$rowCount.'="SOS",15,0)');
EDIT #2
As a way of debugging, for row #2 (ie cell Q2) that formula should be
=IF(G2="SOS",15,0)
for row #3 (cell Q3) it should be
=IF(G3="SOS",15,0)
etc
Do some basic debugging to be sure that your PHP is concatenating the formula value correctly

Related

Excel date is changed to different date in mysql

I am trying to import the excel file to mysql database. I have got date and IMEI field in excel to import to database. But while importing to database my date is changd to different date and IMEI no is changed to exponential format. How can I resolve that problem.
here is the picture.
And here is the code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal";
//$exceldata = array();
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Kolkata');
include 'Classes2/PHPExcel/IOFactory.php';
if(isset($_FILES['file']['name'])){
// $file_name = $_FILES['file']['name'];
// $ext = pathinfo($file_name, PATHINFO_EXTENSION);
//Checking the file extension
$file_name = $_FILES['file']['tmp_name'];
$inputFileName = $file_name;
if(is_uploaded_file($inputFileName)){
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
//Table used to display the contents of the file
echo '<center><table style="width:50%;" border=1>';
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL, TRUE, FALSE);
//check whether member already exists in database with same email
$prevQuery = "SELECT id FROM activereport WHERE aIMEI = '".$rowData[0][1]."' ";
// $prevResult = $con->query($prevQuery);
$prevResult = mysqli_query($con,$prevQuery);
$count = mysqli_num_rows($prevResult);
if($count > 0){
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $rowData[0][2] . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$rowData[0][2]."')";
}
if (mysqli_query($con, $sql)) {
$exceldata[] = $rowData[0];
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
echo '</table></center>';
//redirect to the listing page
header("Location: Import_Active_Data.php");
}
else{
echo '<p style="color:red;">Please upload valid</p>';
}
}
?>
One reason for this behavior could be the way excel stores dates: by counting the days since Jan 1, 1900. if you pass that as an argument to your sql query, it could do weird things.
Try converting the excel date to a string first and pass that to the sql query.
So, I'd change this block:
if($count > 0){
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $rowData[0][2] . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$rowData[0][2]."')";
}
into this:
if($count > 0){
// Date-to-string conversion start
$exceldate = $rowData[0][2];
$phpdate = new DateTime();
$phpdate->setDate(1899, 12, 30);
$dateint = new DateInterval("P" . $exceldate . "D");
$phpdate->add($dateint);
$datestring = $phpdate->format("Y-m-d");
// Date-to-string conversion end
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $datestring . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$datestring."')";
}
Instead of using the rowData[0][2] directly, this will convert the value of that Excel cell (2017-11-11 = 43050) into a php-string ('2017-11-11'), which you can then pass to the sql query.

Php mysql Get&Post query to excel

I have a page that posts to index page like
index.php?coursecode=COURSECODEHERE
My non-variable query works well. Gives me all table as excel file.
I need to use this query with variables.
<?php
require_once('dbconnect.php');
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "SELECT * FROM courses WHERE coursecode POSTED VARIABLE COURSECODE HERE";
$setRec = mysql_query($setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "\n no matching records found\n";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Reoprt.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
?>
How can i do that ?
1.- mysql_ is deprecated, switch to PDO or mysqli ASAP
2.- Always sanitize the input, you never know who may call your link and insert stuff (or delete stuff) from your database.
Said that, you can do something like:
$setSql = "SELECT * FROM courses WHERE
coursecode LIKE '".sanitizeThisShit($_GET["coursecode"])."'";

downloading db records in csv but getting blank rows

Guys this my code downloads records from mysql as csv but wheresoever in rows there is any value with a comma , it does not download and i get a blank row instead
what could be this solution for this
here is my code
require_once('config.php');
$u =$_REQUEST['u'];
$cs =$_REQUEST['cs'];
$y =$_REQUEST['y'];
$d =$_REQUEST['d'];
$m =$_REQUEST['m'];
$date = "$y-$m-$d";
$todays = date("d-m-Y");
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Mortgage-'.$u.'-Records-'.$date.'.csv');
//select table to export the data
$select_table=mysql_query("SELECT * FROM records WHERE user ='".$u."' AND status ='".$cs."' AND DATE_FORMAT(posted, '%Y-%m-%d') = '$date' ORDER BY id DESC");
$rows = mysql_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysql_fetch_assoc($select_table);
}
// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';
// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('', $field_name) . '';
}
echo $separate . $field_name;
//sepearte with the comma
$separate = ',';
}
//make new row and line
echo "\r\n";
}
really appreciate your time and help
Change your first part of the code like this:
require_once('config.php');
$u =$_REQUEST['u'];
$cs =$_REQUEST['cs'];
$y =$_REQUEST['y'];
$d =$_REQUEST['d'];
$m =$_REQUEST['m'];
$date = "$y-$m-$d";
$todays = date("d-m-Y");
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=Mortgage-'.$u.'-Records-'.$date.'.csv');
//select table to export the data
$select_table=mysql_query("SELECT * FROM records WHERE user ='".$u."' AND status ='".$cs."' AND DATE_FORMAT(posted, '%Y-%m-%d') = '$date' ORDER BY id DESC");
$i = 0;
while($rows = mysql_fetch_assoc($select_table);)
{
if($i === 0) {
getcsv(array_keys($rows));
}
getcsv($rows);
$i++;
}
And do this change in function getcsv - replace this code:
$field_name = '' . str_replace('', $field_name) . '';
with this:
$field_name = '"' . $field_name . '"';
But instead of using mysql_query try to implement PDO because mysql lib is prune to mysql injection and will is deprecated in new php versions.

Make calculations in csv with php

First let me introduce myself:
Im 33. 'Living in the Netherlands and i'm a newbe if it comes to php :)
I have a csv file on my vps httpdocs\data\1day.csv . In this file there are two columns: datetime and value. The file looks like this:
"datetime","value",
"2016-01-02 10:50:01","1060.9",
"2016-01-02 10:45:01","1060.6",
I want to make a simple calculation to the file 1day.csv and save it to another csv file. Let's say the caluclation will be value * 5:
"datetime","value","value2",
"2016-01-02 10:50:01","1060.9","5304.5",
"2016-01-02 10:45:01","1060.9","5304.5",
The calculation needs to be done over the whole "value" column.
I want to do this with php and let a cronjob execute this script every x minutes.
Can anybody help me in the right direction?
I would maybe do it more simple. If you didn't know how many columns you could do the extra loops to get column names, but it does not look necessary.
$output = "datetime, value1, value2\n"; // Column names
while ($row = mysql_fetch_array($sql)) {
$output .='"' . $row[0] . '" ,';
$output .='"' . $row[1] . '" ,';
$output .='"' . ($row[1] * 5) . '"';
$output .="\n";
}
#riggsfolly
Ok. This is what i got so far:
// Database Connection
$host="localhost";
$uname="xxxxx";
$pass="xxxxx";
$database = "xxxxx";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or
die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
// Fetch Record from Database
$output = "";
$table = "quotes"; // Enter Your Table Name
$sql = mysql_query("select datetime, value from $table where type = '5' order by datetime desc limit 333");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Save the file
$directory = "/var/www/vhosts/domain.nl/httpdocs/data/";
$filename = "1day.csv";
$fd = fopen ("$directory" . $filename, "w");
fputs($fd, $output);
fclose($fd);
exit;
The part where i get stuck is to add the extra column with the calculated value.

Failing to recognize fetch_assoc method

I'm trying to upload an excel file to my site and save the data in my database, however i'm failing to do so and getting: Fatal error: Call to undefined method mysqli::fetch_assoc() ... But i'm not sure how to handle it, and i haven't found a question related on SO, any help?
function getSchedule($filepath,$con,$filename){
require_once 'excel/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($filepath);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
list($location, $date) = explode('-', $filename, 2);
$LastChange = date('d/m/Y h:i:s');
$Status='Open';
$servername = "localhost";
$username = "root";
$password = "Js";
$dbname = "jr";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Schedule";
$conn->query($sql);
// output data of each row
while($row = $conn->fetch_assoc()) {
$sql1="DELETE FROM `schedule` WHERE " . $row["Date"]. "='$date'";
$result = mysqli_query($conn,$sql1);
}
$conn->close();
for ($row = 3; $row <= $highestRow; ++ $row) {
$sql="INSERT INTO `schedule` (`Status`,`LastChange`, `Location`,`Date`,`AFNumber`,`Name`,`01-IN`, `01-OUT`, `02-IN`, `02-OUT`, `03-IN`, `03-OUT`, `04-IN`, `04-OUT`, `05-IN`, `05-OUT`, `06-IN`, `06-OUT`, `07-IN`, `07-OUT`, `08-IN`, `08-OUT`, `09-IN`, `09-OUT`, `10-IN`, `10-OUT`, `11-IN`, `11-OUT`, `12-IN`, `12-OUT`, `13-IN`, `13-OUT`, `14-IN`, `14-OUT`, `15-IN`, `15-OUT`, `16-IN`, `16-OUT`, `17-IN`, `17-OUT`, `18-IN`, `18-OUT`, `19-IN`, `19-OUT`, `20-IN`, `20-OUT`, `21-IN`, `21-OUT`, `22-IN`, `22-OUT`, `23-IN`, `23-OUT`, `24-IN`, `24-OUT`, `25-IN`, `25-OUT`, `26-IN`, `26-OUT`, `27-IN`, `27-OUT`, `28-IN`, `28-OUT`, `29-IN`, `29-OUT`, `30-IN`, `30-OUT`, `31-IN`, `31-OUT`) VALUES ('".$Status."', '".$LastChange."','".$location."','".$date."',";
for ($col = 0; $col < ($highestColumnIndex -1); ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($col==($highestColumnIndex -2)){
$sql.="'$val'";
}else{
$sql.="'$val', ";}
}
echo "Index:".$highestColumnIndex."<br>";
if($highestColumnIndex < 63){
$temp = 63 - $highestColumnIndex;
for($i = 1;$i <= $temp; $i++){
if($i == $temp){
$sql.=",''";
} else{
$sql.=", '',";
}
}
}
$sql .=")";
if ($con->query($sql) === TRUE) {
} else {
echo "<br><br>Error: " . $sql . "<br>" . $con->error;
}
}//End For Each Row
}//End For Each Worksheet
}//End getHours Function
From php.net:
array mysqli_result::fetch_assoc ( void )
This means that you should provide it with a result of a query, not a connection. Change your code to this and it should work
$results = $conn->query($sql); //assign query to a variable and get mysqli_result in return
while($row = $results->fetch_assoc()) { //use that in the while loop
You are overwriting the connection object $conn.Use
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
Try this:
$sql = "SELECT * FROM Schedule";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {

Categories