PHPExcel -- Color part of XLSX table - php

I need your help, I have a table with ~ 2000 rows, I would color a part of cells (Ex. Row: 1000 to Row: 2000).
The second question is: how can I format the date automatically? I have this format "21/12/2014 15:08:23" I would format it into "21/12/2014" automatically when I write the new xlsx file.
What can I do?

To colour the rows:
$objPHPExcel->getActiveSheet()->getStyle('A1000:IV2000')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('A1000:IV2000')
->getFill()
->getStartColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE);
To format dates:
Make sure that you're setting your date values as an Excel serialized timestamp
$myDate = "21/12/2014 15:08:23";
$myDateValue = DateTime::createFromFormat('d/m/Y H:i:s', $myDate);
$excelTimeStamp = PHPExcel_Shared_Date::PHPToExcel($myDateValue);
$objPHPExcel->getActiveSheet()
->setCellValue('A1', $excelTimeStamp);
$objPHPExcel->getActiveSheet()
->getStyle('C9')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY);
All of this is covered in the documentation and in the examples provided with the PHPExcel package

Related

PHPSpreadsheet: Formatting a cell for time also includes the date

I am trying to format a time cell using PHPSpreadsheet but it seems to be including the date as well when looking at the formula bar. There also seems to be some inconsistency when converting from a string, datetime object or unix timestamp.
<?php
include '../vendor/autoload.php';
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$times = [
'16:00:00',
new \DateTime('16:00:00'),
\strtotime('16:00:00'),
'2020-04-04 16:00:00',
new \DateTime('2020-02-04 16:00:00'),
\strtotime('2020-02-04 16:00:00'),
];
$format = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME1;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
foreach ($times as $i => $time) {
$sheet->setCellValue('A' . ($i+1), \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($time));
$sheet->getStyle('A' . ($i+1))->getNumberFormat()->setFormatCode($format);
}
$writer = new Xlsx($spreadsheet);
$writer->save('test.xlsx');
From \PHPOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME1: const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
Is this a bug or intended functionality? Considering as const FORMAT_DATE_DATETIME = 'd/m/yy h:mm'; does include some date parameters I think there's something wrong happening.
Here's some screenshots of what happens:
But if we type in "5:00 AM" into a cell, the formula bar does not include the date:
Here is the screen that pops up from Right Click > "Format Cell":
Can someone please tell me if I'm doing something wrong, thankyou.
I figured out how to fix this problem: You need to calculate the Excel representation of the timestamp and then get only the numbers after the decimal place.
<?php
$timestamp = new \DateTime('16:00:00');
$excelTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($timestamp);
$excelDate = floor($excelTimestamp);
$time = $excelTimestamp - $excelDate;
From the documentation:
In Excel, dates and Times are stored as numeric values counting the number of days elapsed since 1900-01-01. For example, the date '2008-12-31' is represented as 39813. You can verify this in Microsoft Office Excel by entering that date in a cell and afterwards changing the number format to 'General' so the true numeric value is revealed. Likewise, '3:15 AM' is represented as 0.135417.
I hope this helps anybody else stuck with this problem.
You must set the right number format see for more information the official sample documentation.
The number format that you set is 'h:mm AM/PM' means that there is no date included only the time.
When you change to 5 PM you overwrite the content and the number format will used.
If you will have a date you should try to set 'd/m/yy h:mm AM/PM'.

How can set format datetime [PHPExcel]

set format datetime with php
and output excel
date_default_timezone_set('Asia/Bangkok');
$objPHPExcel->getActiveSheet()->SetCellValue('S1', 'Show DateTime');
$dateValue = PHPExcel_Shared_Date::PHPToExcel( strtotime('23-Apr-1989 17:05:50') );
$objPHPExcel->getActiveSheet()
->setCellValue('S2', $dateValue);
$objPHPExcel->getActiveSheet()
->getStyle('S2')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
but output
How can show data on Excel 23/04/1989 17:05:50 and excel type Date
You currently use the predefined constant PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH for your number format.
If you replace that by your desired format, everything should be ok: 'dd/mm/yyyy hh:mm:ss'
Also see the documentation for setFormatCode(): http://apigen.juzna.cz/doc/ouardisoft/PHPExcel/class-PHPExcel_Style_NumberFormat.html#_setFormatCode

Custom date format in PHPExcel

In my excel file I am building from PHP the first row is the header one. I need to put there several dates as column header. Each date is (in dd/mm/yyyy format) 15/mm/yyyy starting from 15/01/2007 and ending with 15/12/2018 stepping month by month.
My code is this:
for($anno = $annoMin; $anno<=$annoMax; $anno++){
for($mese = 1; $mese <= 12; $mese++){
$mese = sprintf("%02s", $mese);
$periodo = '15/'.$mese.'/'.$anno;
$periodo = strtotime($periodo);
$periodo = PHPExcel_Shared_Date::PHPToExcel($periodo);
array_push($header_array,$periodo);
}
}
I build the date as a string, convert it into a unix timestap, convert it into an excel date and push it into the $header_array.
Then I draw the cells in the excel:
$ews->fromArray($header_array, ' ', 'A1');
Finally I format the cells where there is a date as:
$ews->getStyle('U1:EJ1')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY);
ISSUES ARE:
Actually my code is returning 'False' for each cell with a date;
I need to add a custom mask that is not listed in the PHPExcel library: MM/YYYY to be shown in each cell.
For the first issue: I have checked different SO questions and followed mainly this one. with no luck.
Problem is here:
$periodo = '15/'.$mese.'/'.$anno;
$periodo = strtotime($periodo);
which would give a string values of 15/1/2015, 15/2/2015... ``15/12/2015that you're then attempting to convert to a unix timestamp usingstrtotime()`.
If you read the PHP Docs on date formats used by the strtotime() function, you'll see that a / separator tells PHP that the date string is US date format.... i.e. mm/dd/yyyygiving a month value of15` in every case, and (of course) there is no month 15
Either use a dash (-) rather than a / to indicate European (dd-mm-yyyy) rather than US date format
$periodo = '15-'.$mese.'-'.$anno;
$periodo = strtotime($periodo);
or re-order the values to use US format
$periodo = $mese.'/'.'15/'.$anno;
$periodo = strtotime($periodo);
And for the second part of your question.... you can supply almost any format mask that MS Excel recognises, you're not restricted to the built-in formats; so:
$ews->getStyle('U1:EJ1')
->getNumberFormat()
->setFormatCode('mm/yyyy');
The format code is simply a string value

Error Import Excel Date PHP

I have a problem trying to upload an excel to my database through PHP.
The format I have in the excel is dd/mm/yyyy and my sql needs yyyy/mm/dd
$_DATOS_EXCEL[$i]['ship_day']= $objPHPExcel->getActiveSheet()- >getCell($headings['Ship Date'].$i)->getFormattedValue();
I tried
getFormattedValue('YYYY/MM/DD');
but doesnt work
I really appreciate if you can help me out with this.
If your cell value really is an Excel serialized date/time value, and you know which cells contain these dates, then you can convert it directly to a PHP DateTime object
$dto = PHPExcel_Shared_Date::ExcelToPHPObject(
$objPHPExcel->getActiveSheet()
->getCell($headings['Ship Date'].$i)
->getValue()
);
$_DATOS_EXCEL[$i]['ship_day'] = $dto->format('Y/m/d');
or to a Unix Timestamp
$unixTimestamp = PHPExcel_Shared_Date::ExcelToPHP(
$objPHPExcel->getActiveSheet()
->getCell($headings['Ship Date'].$i)
->getValue()
);
$_DATOS_EXCEL[$i]['ship_day'] = date('Y/m/d', $unixTimestamp);
Add three line after
"$_DATOS_EXCEL[$i]['ship_day']= $objPHPExcel->getActiveSheet()- >getCell($headings['Ship Date'].$i)->getFormattedValue();"
this line......
$rearrange=$_DATOS_EXCEL[$i]['ship_day'];
$explode = explode("/",$rearrange);
$_DATOS_EXCEL[$i]['ship_day']= $explode[2]."/".$explode[1]."/".$explode[0];

PHPExcel Date Format

I am getting an output from MS SQL server in the '2012-08-09 00:00:00' (without quotes) format.
However, when I write it to excel file I'm unable to write it in date format to have dd mmm yyyy formatting on excel.
As a result i tried to write in format =date(2012,08,09) as a formula to the respective cells.
But I don't want to output it as a formula but rather the value '09 Aug 2012' with the data type integrity intact. How do I do this? Or is there a simpler method?
I read through the documentation but it was not clear to me, thought I would ask for clarification.
Regards.
Sorry for not being detailed enough.
I am using the PHPExcel library.
From my sql array, i use the following:
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],5,2);
$t_day = substr($xls_column_datas["colname"],8,2);
$t_format = $t_year . "," . $t_month . "," . $t_day ;
$t_format = '=date('.$t_format.')';
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($data_column_num, $data_row_num, $t_format );
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow($data_column_num, $data_row_num)->getNumberFormat()->setFormatCode('[$-C09]d mmm yyyy;#');
in my excel output, it shows column A2 for e.g. =DATE(2012,8,9)
rather than showing up as a formula I want excel to recognize '2012-08-09 00:00:00' is a date time and format it to dd mmm yyyy.
Is this getting clear? Sorry.
Is your problem in getting the date from MS SQL as a date/time, or setting the Excel date?
There is a whole section of the PHPExcel documentation that explains the use of the PHPExcel_Shared_Date::PHPToExcel($PHPDate) and PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) helper methods for converting PHP dates to an Excel datetime stamp value that you set as the cell value, and then you apply a number format mask of one of the date masks such as PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 to that cell
Instead of
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],5,2);
$t_day = substr($xls_column_datas["colname"],8,2);
$t_format = '=date('.$t_format.')';
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($data_column_num, $data_row_num, $t_format );
$objPHPExcel->getActiveSheet()->getStyleByColumnAndRow($data_column_num, $data_row_num)->getNumberFormat()->setFormatCode('[$-C09]d mmm yyyy;#');
try setting
$t_year = substr($xls_column_datas["colname"],0,4);
$t_month = substr($xls_column_datas["colname"],4,2); // Fixed problems with offsets
$t_day = substr($xls_column_datas["colname"],6,2);
$t_date = PHPExcel_Shared_Date::FormattedPHPToExcel($t_year, $t_month, $t_day);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(
$data_column_num, $data_row_num, $t_date
);
$objPHPExcel->getActiveSheet()
->getStyleByColumnAndRow($data_column_num, $data_row_num)
->getNumberFormat()->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14
);
$date = PHPExcel_Style_NumberFormat::toFormattedString($data, "M/D/YYYY");
Though it is unclear what are asking, If you are looking for a date conversion
// convert old date string to YYYYmmdd format
$date = date('d M Y', strtotime($old_date));
this will output date in 09 Aug 2012 format
Why not let the server to the formatting for you? Use this query to format the date
SELECT convert(varchar(15), getdate(), 106)
This will result 11 Sep 2012
SQL SERVER: Date Format

Categories