I want to calculate difference between 2 datetimes in hours with PHPSpreadsheet. This is how Excel does it:
A1 and A2 cells format is:
This is the result on web:
When I change value through PHPSpreadsheet, I get #VALUE! and different value formatting.
$reader = PhpSpreadsheet\IOFactory::createReader("Xlsx");
$target_file = __DIR__ . '/test.xlsx';
$spreadsheet = $reader->load($target_file);
$spreadsheet->getActiveSheet()->setCellValue('A1', '24.6.2020 12:30');
$writer = new PhpSpreadsheet\Writer\Html($spreadsheet);
$output = $writer->generateHTMLHeader();
$output .= $writer->generateStyles(true);
$output .= $writer->generateSheetData();
$output .= $writer->generateHTMLFooter();
$doc = new DOMDocument();
#$doc->loadHTML($output);
echo $doc->saveHTML();
I also tried with formatting like this 6/24/2020 14:30 but the result was same (#VALUE!)
$spreadsheet->getActiveSheet()->setCellValue('A1', '6/24/2020 14:30');
Anyone got any idea on how this should be done?
In an Excel document, dates are stored as numbers, not strings. So you need to pass the correct number to setCellValue().
PhpSpreadsheet provides the utility method Date::stringToExcel() to convert strings to Excel dates. You can use it like this:
$date = PhpSpreadsheet\Shared\Date::stringToExcel('2020-06-24 12:30');
$spreadsheet->getActiveSheet()->setCellValue('A1', $date);
Related
I'm having difficulty with PHPSpreadsheet when creating an XLSX file and attempting to write large numbers of decimal places to numerical values.
PHPSpreadsheet is rounding my 14 decimal place numbers, but I need them stored exactly as presented.
I'm using setFormatCode('0.00000000000000') as described in the documentation, but it's not working as I would expect.
Here's my test code:
<?php
require __DIR__ . '/vendor/autoload.php'; // Installed via composer
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$array = [
0.03790728347833,
1345.28748532874927,
121345.18248762894914, // all 14 DP
];
$format = '0.00000000000000'; // 14 DP
// write the data
$spreadsheet->getActiveSheet()
->fromArray($array, null, 'A1');
// Format the cells
$spreadsheet->getActiveSheet()->getStyle('A1:C1')->getNumberFormat()->setFormatCode($format);
// Column sizing
foreach(range('A','C') as $columnID)
{
$spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("test.xlsx");
// A1 = 0.03790728347833 - same
// A2 = 1345.28748532870000 - rounded
// A3 = 121345.18248763000000 - rounded
Could anyone provide a way to store this many decimal places without rounding?
This appears to be a limitation of Excel rather than PHPSpreadsheet.
Excel is limited to 15 significant figures according to Wikipedia.
I am trying to calculate age based on birth date. Excel Formula is
=DATEDIF(K4,DATE(2014,3,31),"Y")=DATEDIF(K4,DATE(2014,3,31),"YM")
Which shows 9.7 if value in cell K is 2004-08-01 this is perfect but I am not able to set this formula in excel sheet using PHPExcel.
Here is code what I am trying
$date = date('2014,03,31');
for($i=3;$i<=100;$i++){
$objPHPExcel->getActiveSheet()-setCellValue('AQ'.$i,'=DATEDIF(K'.$i.',DATE('.$date.'),"Y")'.'& . & '.'DATEDIF(K'.$i.',DATE('.$date.'),"YM")');
}
What is wrong with the code why excel file not opening after download and showing fileformat or file extension not valid.
Your Excel formula concatenation is with an invalid .. Assuming you want to display a . between the Year and the Months then you need to treat it as a string literal ("."):
$date = date('2014,03,31');
for($i=3;$i<=100;$i++){
$objPHPExcel->getActiveSheet()-setCellValue(
'AQ'.$i,
'=DATEDIF(K'.$i.',DATE('.$date.'),"Y")'.'& "." & '.'DATEDIF(K'.$i.',DATE('.$date.'),"YM")'
);
}
not tested, try this,
$date = date('2014,03,31');
for($i=3;$i<=100;$i++){
$objPHPExcel->getActiveSheet()->setCellValue('AQ'.$i,'=DATEDIF(K'.$i.',DATE('.$date.'),"Y")'.'& . & '.'DATEDIF(K'.$i.',DATE('.$date.'),"YM")');
}
I have a script which imports a csv file into a MySQL table using explode to separate the fields. my last field in the csv file is a date time field but in the incorrect format as per image below:
I want to use the below code to insert the csv into MySQL and change the format of the last column from mm/dd/yyyy hh:mm:ss am/pm to the MySQL format of yyyy-mm-dd hh:mm:ss
Existing working script (just doesn't import date time field as format is wrong):
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "LoadsOverWB.csv";
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
$query = "replace into $databasetable(loadnumber,weighbillnumber,VehicleRegistration,haulier,vehicleweight,rolledproductkg,hegrosskg,roofinhkg,nonmetalkg,wbtotalkg,datetime) values('','$linemysql');";
else
$query = "replace into $databasetable(loadnumber,weighbillnumber,VehicleRegistration,haulier,vehicleweight,rolledproductkg,hegrosskg,roofinhkg,nonmetalkg,wbtotalkg,datetime) values('$linemysql');";
$queries .= $query . "\n";
#mysql_query($query);
}
Thanks in advance as always, much appreciated.
Just add two lines after exploding
$key = count($linearray);
$linearray[$key - 1] = date('Y-m-d H:i:s',strtotime($linearray[$key - 1]));
$linemysql = implode("','",$linearray);
Also before inserting print_r the result to see if the format has been changed.
EDITS :
Looking at the library you are using i assume the last index of each row is your date column(TIME OVER WEB). So i am count the length of array and count - 1 gives me the last index so than i am applying php date function.
date('format',strtotime(datevalue))
strtotime converts the string given to numbers like 32431234 and then date function takes tow parameters. Format and number. I am sure that's enough for you to understand.
First of all you should check out fgetcsv(). You will get each row into an array, and be able to process it a lot better.
And to answer your question, you need to format the date.
$date = $linearray['date']; // or what key your date has
$date = date('Y-M-d H:i:s', strtotime($date));
this is my first question in stackoverflow. I am trying to use PHPExcel to create an HTML table from .xlsx file. You can find my project in:
http://rahulr92.x10.mx/excel/index.php
Login with username 'admin' and you will find an option to 'View Table'. That page displays a table from previously uploaded .xlsx file. I am new to PHPExcel and used some standard code I found online. Here it is:
<?php
require_once '/Classes/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("..\excel.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$user=strtolower($_GET['user']);
$r_count=0;
echo '<table border="1">' . "\n";
for ($row = 5; $row <= $highestRow; ++$row) {
if ($row <7 || $user=="admin" || strstr(strtolower($objWorksheet->getCellByColumnAndRow(8, $row)->getValue()),$user ))
{
if($row>7)$r_count++;
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
if(PHPExcel_Shared_Date::isDateTime($objWorksheet->getCellByColumnAndRow($col,$row)))
echo '<td>' . date("d M Y",PHPExcel_Shared_Date::ExcelToPHP($objWorksheet->getCellByColumnAndRow($col, $row))) . '</td>' ;
else
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
}
}
echo '</table>' . "\n";
echo "No. of Entries: ".$r_count;
?>
Sorry for the sub-optimal code. When I run the php file, I get a table and all strings in it are displayed properly but datetime and number fields are filled with seemingly random gibberish. Please have a look at it from the above link. I have done some research and found out about the isDateTime() function that way. But it isn't working or probably is used wrongly. I am having a tight deadline for this project, so it would be great if anyone could point me in the right direction. Really sorry if the answer was very obvious. Thanks a lot in advance.
Rahul
Don't set $objReader->setReadDataOnly(true); if you want to be able to identify date/time values... Excel stores dates/times as floating point numbers, and the only way to differentiate a number from a date/time is using the format masking: isDateTime() uses that format masking to identify if a value is a number or a date/time... $objReader->setReadDataOnly(true) tells the file reader to read only the data (the numbers) and to ignore format masks, so it only reads the raw data.
However, I'm not sure I understand exactly what you mean by "random gibberish"... numbers should still display as numbers... can you please give an example.
EDIT
Note that cell methods such as getFormattedValue() will return numbers as they are format masked in the workbook, so date/time values will be formatted as dates/times, numbers will be displayed with appropriate number of decimal places, thousand separators or currencies or percentages (if they had the appropriate formatting in the Excel file), so you don't need to test for isDateTime().... as long as $objReader->setReadDataOnly(true) wasn't set for teh reader.
I'm loading an Excel file that has cells with time data, e.g. 08:00:00. But when I try to read those cells with getValue(), it returns some floating point numbers instead of the actual time (in case of 08:00:00, it returns 0.3333333). Here's my code:
$objPHPExcel = PHPExcel_IOFactory::load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
echo $objWorksheet->getCellByColumnAndRow(3, 5)->getValue();
How do I bypass this weird conversion?
PHPExcel 1.7.6 and Excel 2003 Worksheet (.xls)
You need to apply cell format for this:
$cell = $objWorksheet->getCellByColumnAndRow(3, 5);
$cell_value = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), 'hh:mm:ss');
echo $cell_value;