PHPExcel setting date format without writing every single value - php

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

Related

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?

How to read a date with ExcelBundle [Symfony Bundle]

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';
}

I need to import an excel file into database using PHPExcel the issue is with the date

I need to import an excel file into database using PHPExcel the issue is with the date,The date can be in any format in excel file.
when the date in excel file is in this format 12/12/2012 (m/d/y) it save correctly into database but if the format date in excel file is this 24/11/2014(d/m/y) it upload blank
when 24/12/2012(d/m/y) the value is 2036-03-01
$data = $objWorksheet->getCellByColumnAndRow($col, $row);
if(PHPExcel_Shared_Date::isDateTime($data)){
$cellValue = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
$dateValue = PHPExcel_Shared_Date::ExcelToPHP($cellValue);
$dob = date('Y-m-d',$dateValue);
} else{
$datedata = "NULL";
}
hope you can help me guyz
The important thing here to be reminded of is that Excel stores dates and times as serial date or serial date-time. This is the number of days since Jan 0, 1900 plus a fraction of a 24 hour day. This article contains a good explanation.
The fact that you are getting a negative serial date like -454654643 probably mean that the formatt type of the cells in your Excel spreadsheet is incorrect.
There are two things you need to verify:
In Excel, use Ctrl + ` to reveal the serial date value of each date cell. None of these values should be negative. Then use Ctrl + ` to switch back to the default formatted-date view. (The ` key is the one above the tab key on your keyboard).
Right-click on the date cells, navigate to Format Cells > Number > Date > Type, and ensure that the date format specified in Type matches your intent. So if your dates are to be interpreted as d/m/y, make sure the Type matches. And likewise, for m/d/y.
Hope this helps.
I would try formatting the data from the SELECT statement you are using. Let the DB do the time work. Let the PHP script to the real work.
Here is a link to the MYSQL Reference guide that explains all the many way to play with date and time on the database side.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
What you are looking for is
SELECT date_format('2014-10-13 22:00:00, '%m-%d-%Y') from <table> WHERE <column> = <data>
this will output 10-13-2014
From here you should be able to figure out the rest.

convert date data into mysql date format

I want to convert the data on which I have the format
$dateToday = date("d-m-Y");
so the value of $dateToday is 27-12-2012
Then I want to save it to the database with the mysql data type date. How to keep the value of 27-12-2012 it can be stored in the mysql database with the format 2012-12-27?
Help me please. Thank you
Yes, you can convert the date with strtotime();
$dateToday = date("d-m-Y");
$newDate = date("Y-m-d", strtotime($dateToday));
OUTPUT: 2012-12-27
And then you can store data to your database.
When you have to recover the date you can reverse this operation like this:
$dateFromDatabase = "2012-12-27";
$reverseDate = date("d-m-Y", strtotime($dateFromDatabase));
OUTPUT: 27-12-2012
(corrected "Y-m-d" to "d-m-Y" in 2nd date call)
this is how it works:
You have to store your data in the proper mysql format. It will allow you to make whatever ordering, aggregating, filtering and calculating your dates.
But when you need to display your data, you may convert it in whatever format you wish, using mysql DATE_FORMAT() function:
SELECT DATE_FORMAT(dt,'%d-%m-%Y') as dtf FROM TABLE
will give you dtf field formatted in your custom format
i'll show u how to do that.
To explain i create one table called testtable1 it contain only one column called
col1 of type DATE
Table creation query is given below
CREATE TABLE `testtable1` (
`col1` DATE NULL DEFAULT NULL
)
Following query will work as you need.
In the first line i declared a string variable. In the second line i converted that string to your required date format and inserted into table.
set #var1='27-12-2012';
insert into testtable1 values(STR_TO_DATE(#var1, '%d-%m-%Y'))
You could also try to use the mysql function for converting to a date from a string, i.e
STR_TO_TIME
.
The SQL query could be
INSERT INTO foo_table (foo_date)
VALUES (STR_TO_DATE('27-12-2012','%d,%m,%Y'))
If you want to store data in MYSQL table in this format, you need to declare the column as varchar.
Because the datetime store date in a different format like 'yyyy-mm-dd hh:mm:ss'
The output is wrong This cannot show the date from the database .This show 1970/01/01.....
$date=Date($year."/". $month."/". $day);
$date=Date("Y-m-d", strtotime($date));
echo $date;enter code here
Try this
$dateToday = date("d-m-Y");
$dateForMysql = date('Y-m-d', $dateToday));

Categories