How to read a date with ExcelBundle [Symfony Bundle] - php

I'm having an issue while I'm trying to read cell value with $cell->getCalculatedValue() of a DateTime cell.
The excel file value is 28/2/15 (in format d/m/y) but I get 42063.
Is this a problem with the format? If it is, how I can solve it?

MS Excel date/time values are a float, not a formatted string, or any other special datatype; and it's only the number formatting mask that differentiates them from any other float
getCalculatedValue() will handle any formulae, but won't apply any formatting, so you'll simply get the float value back
however
getFormattedValue() will calculate any formula for the cell, but also apply any number formatting mask, so a "date" will be returned as a formatted string dependent on the number format mask for that cell
EDIT
The formatted string returned is dependent on the number format mask used.... unfortunately some MS Excel date format masks are locale aware, but PHPExcel is not, so if the cell uses one of these masks then the result may not be formatted as you'd want.
You can apply manual formatting for a cell value, using a format mask of your choice:
$result = PHPExcel_Style_NumberFormat::toFormattedString(
$cell->getCalculatedValue(),
PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY
);
or
$result = PHPExcel_Style_NumberFormat::toFormattedString(
$cell->getCalculatedValue(),
'dd/mm/yy'
);
Alternatively, you can convert that MS Excel serialized timestamp to a unix timestamp using
$result = PHPExcel_Shared_Date::ExcelToPHP(
$cell->getCalculatedValue()
);
or to a PHP DateTime object
$result = PHPExcel_Shared_Date::ExcelToPHPObject(
$cell->getCalculatedValue()
);
and then use normal PHP date() or DateTime::format() masking to format it however you want
EDIT #2
To identify if a cell contains a date:
if (PHPExcel_Shared_Date::isDateTime($cell)) {
echo 'Cell ', $cell->getCoordinate(), ' contains a date value';
}

Related

Format date function - Customizing output

I am new on PHP and I am trying to retrieve date from my database and format it from this: yyyy-mm-dd hh:mm:ss to this format: dd-mm-yyyy hh:mm:ss. My first thought was to convert the format before store in the server, but I have read that it is a bad practice, so I am trying to do it when outputting the data.
The point is, it is not working, when I use Format function it changes the format, but in a wrong way.
In this example I am using 'MM/dd/yyyy' format string, but I have already tryied with different formats and the output is always the same.
The table column is in datetime format, but I have experimented with text and varchar formats, in the first case the output is the same as the one from datetime format and in the second case I just receive the first four numbers.
One more thing, I am using PDO.
This is my query:
public function funcaoTesteGetValues() {
$query = "SELECT teste_data,FORMAT(teste_data,'MM/dd/yyyy') AS 'nova_data' FROM teste";
$stmt = $this->conexao->prepare($query);
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_OBJ);
}
Here goes the output:
[teste_data] => 2015-12-04 04:04:00 => database format (datetime)
[nova_data] => 20,151,204,040,400 => output formatted
What I need:
04-12-2015 04:04:00
FORMAT() is for numbers rounded to a certain number of decimal places. You want DATE_FORMAT() with the correct format identifiers
DATE_FORMAT(teste_data,'%m/%d/%Y') AS 'nova_data'
Note This is only if your database server is MySQL.

PhpSpreadsheet's formating the date importing from XLSX

Good Day. I use PhpSpreadsheet's library to import xlsx.
In The column I in xlsx I have this value 20/10/1970 00:00:00 displaying like 1970-10-20 00:00:00 but when I import it:
$dataArray = $spreadsheet->getActiveSheet()
->rangeToArray(
'A2:AO3', // The worksheet range that we want to retrieve
NULL, // Value that should be returned for empty cells
NULL, // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
TRUE, // Should values be formatted (the equivalent of getFormattedValue() for each cell)
TRUE // Should the array be indexed by cell row and cell column
);
I receive strange ["I"] => float(25861) Please Help me to get Carbon data in this field.
If I try to convert this float like a timestamp I receive 01/01/1970 not 10/20/1970
Other date I receive like ["J"] => float(43195.4092014)
In Excel dates are not the same as in other software/programming languages.
Excel counts from 1900-01-01 unlike UNIX that counts from 1970-01-01.
The number returned is a float value of the number of days from 1900-01-01, and the fraction of the float is the time of the day.
As an example 25861.5 is 1970-10-20 12:00 ("Y-m-d h.i").
To convert to UNIX you should take the returned value - 25569 (1970-01-01 in Excel) and multiply with 86400 (one day in seconds).
See here:
https://3v4l.org/AudMn
In Excel if you format 25861 and 25569 as dates:
The other float you got 43195.4092013889
echo date("Y-m-d h:i", (43195.4092013889-25569)*86400); //2018-04-05 11:49 (mind the timezones)
https://3v4l.org/mMZQ4
Another way to solve that feature is getting the active sheet from our object PHPSpreadSheet and change the style as follows:
$sheet = $PhpSpreadSheetObject->getActiveSheet();
$sheet->getStyle("A1:Z1")->getNumberFormat()->setFormatCode("YYYY-MM-DD");

PHPExcel putting string date into .xls

guys. I have dates at DB as strings "d/m/Y".
When I put this dates into Excel, it shows me normal dates like 03/10/2000, but when I click on the cell, it show me the value '03/10/2000. So, the value is string, and not date as required for me.
So, I transformed the date from DB to a PHP date object and get sure with var_dump that date is Date object with that code :
$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
$date->format('m/d/Y');
but anyway, the values in generated .xls are with ' before value.
Why it appears and how can I solve it ?
MS Excel stores dates as a serialized timestamp, the number of days since 1st January 1900 (or 1st January 1904 if using the Mac calendar). To store a value as a date (and not simply as a string), you need to convert your string date to a serialized timestamp, and then set the format mask for the cell.
$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
$excelDate = PHPExcel_Shared_Date::PHPToExcel($date);
Set $excelDate as the cell value
$objPHPExcel->getActiveSheet()->setCellValue('C11', $excelDate );
and then apply the format mask to that cell
$objPHPExcel->getActiveSheet()
->getStyle('C11')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
The 02types.php example script in the `/Examples` folder demonstrates this
EDIT
You can (and it's more efficient to) apply a style to a range of cells: just specify the range in the getStyle() call.
$objPHPExcel->getActiveSheet()
->getStyle('C11:C200')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
To get details of available format: PHPExcel has a number of pre-defined formats built-in, and those can be found as constants in Classes/PHPExcel/Style/NumberFormat.php. However, you're not limited to that set of formats; and (in the same way that MS Excel lets you define "custom" formats) you can simply pass a string defining the format (e.g. "d-mmm-yyyy") using pretty much any of the rules that can be used for MS Excel number format masks as the format

PHPExcel date not appearing

I am trying to format a PHP date() object into a format that Excel can read as a date rather than as a string.
$row[] = PHPExcel_Shared_Date::PHPToExcel(date('d-m-y', strtotime($worksheet_one_job['Job']['date_of_order'])));
$worksheet_one->fromArray($row, NULL, $columnID.$rowID);
The format of the field $worksheet_one_job['Job']['date_of_order'] in the database is DateTime (2016-06-28 00:00:00)
When I check this in Excel it prints nothing at all, any ideas how I can set the cell as a date format that Excel can read rather than as a string?

PHPExcel setting date format without writing every single value

My current version of code for outputting to an Excel file is as follows:
I have an array of the column names and an array of all of the data:
$objPHPExcel->getActiveSheet()->setTitle($titleArr[$i]);
$objPHPExcel->getActiveSheet()->fromArray($headersArr[$i], NULL, 'A1');
$objPHPExcel->getActiveSheet()->fromArray($dataArr[$i], NULL, 'A2');
The only other thing I've been doing is to autosize the columns
$objPHPExcel->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
Is there any way to let the sheet be filled with data from the array and just tell excel that certain columns are actually in a specific format?
The following creates a custom field in Excel, rather than a date field. It sorts but I have to manually tell it to treat it like a number.
$objPHPExcel->getActiveSheet()->getStyle($col . '2:' . $col. '500')->getNumberFormat()->setFormatCode('yyyy-mm-dd hh:mm:ss');
Is there any way to get it to treat it like a date without having to write each cell manually with statements like:
$objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(3, $currentrow, PHPExcel_Shared_Date::PHPToExcel($timestamp));
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow(3, $currentrow)->getNumberFormat()->setFormatCode('dd/mm/yyyy');
If a whole column is filled with only date values, you can use getStyle() instead of getStyleByColumnAndRow() to get the whole column. Like this:
$objPHPExcel->getActiveSheet()->getStyle('C:C')->getNumberFormat()->setFormatCode('dd/mm/yyyy');
A coordinate in the format A:A is converted to A1:A1048576. The same works for 1:1 which translates to A1:XFD1. See setSelectedCells() in Worksheet.php for the different conversions.
There isn't any such thing as a date field in Excel.... a date is nothing more than a number with a format mask.
But you could try using a cell binder: the cell binder is called whenever you set a value in a cell (unless you set the value explicit). The advanced value binder provided as an option with PHPExcel that recognises most date and time formats and will automatically convert and set a format mask accordingly.
I put after $objPHPExcel->getActiveSheet()->fromArray to set date time in columns as shown below:
while ($row = mysql_fetch_assoc($result)) {
$objPHPExcel->getActiveSheet()->fromArray($row, null, "A".$red);
// Again set row values
$dateValuerr = PHPExcel_Shared_Date::PHPToExcel(strtotime($row[NasDatumPrijemaPredmeti]));
$objPHPExcel->getActiveSheet()->setCellValue("D".$red."", $dateValuerr);
$dateValuerr = PHPExcel_Shared_Date::PHPToExcel(strtotime($row[NjihovDatumPrijemaPredmeti]));
$objPHPExcel->getActiveSheet()->setCellValue("E".$red."", $dateValuerr);
$objPHPExcel->getActiveSheet()->getStyle("A".$red.":AF".$red)->applyFromArray($table_style);
$objPHPExcel->getActiveSheet()->getStyle("A".$red.":AF".$red)->getFont()->setBold(true);
$red++;
};
and then set column
$objPHPExcel->getActiveSheet()->getStyle('D2:E1000')->getNumberFormat()->setFormatCode(exportdatum);
My date is : define('exportdatum', 'dd.mm.yyyy'); // Date
This is date in my MySql DB
MySql Date : 2015-05-01
But I convert in query to
DATE_FORMAT(predmeti.NasDatumPrijemaPredmeti, '%d.%m.%Y') AS NasDatumPrijemaPredmeti

Categories