Date and Datetime using PHPExcel function writes in excel as Text - php

I have a problem with PHPExcel function, this is my code:
<?php
# Load slim WP
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );
# http://phpexcel.codeplex.com/
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
global $wpdb;
$query = "Select
tsales_funnel.ID As ID,
wp_users.display_name As Darijuma_vaditajs,
tcportal_starpnieks.Cp_Name As Starpnieks,
tcportal_stucture.Cp_Name As OWCA,
n_products.Product_Nos As Produkts,
tsales_funnel_mrecord.Product_type as Produkta_kods,
tsales_funnel.Sanems_date as Saņēmšanas_datums,
tsales_funnel_mrecord.Deadline As Deadline,
n_sf_statusi.nosaukums_lv As Statuss,
tsales_funnel_clients.Reg_nr As Klienta_Regnr,
tfirmas_reg.name_in_quotes As Klients,
tsales_funnel_mrecord.Faze_date as Faze_date,
n_sf_fazes.nosaukums_lv As Faze,
tsales_funnel_mrecord.Summa As Apdrošīnājuma_summa,
tsales_funnel_mrecord.Vien_skaits As TRL_skaits,
tsales_funnel_mrecord.Compensa_cena,
tsales_funnel_mrecord.Tirgus_cena,
wp_users02.display_name As Riska_parakstitajs,
comm.Comment as Aizveršanas_komentārs
From
tsales_funnel Left Join
tsales_funnel_mrecord On tsales_funnel.ID = tsales_funnel_mrecord.Funnel_ID
Left Join
tcportal_starpnieks On tcportal_starpnieks.Cp_code = tsales_funnel.Starpnieks
Left Join
tcportal_stucture On tcportal_stucture.Cp_code = tsales_funnel.OWCA Left Join
tsales_funnel_clients On tsales_funnel_clients.Funnel_ID = tsales_funnel.ID
Left Join
tfirmas_reg On tfirmas_reg.regcode = tsales_funnel_clients.Reg_nr Left Join
wp_users On tsales_funnel.Darijuma_vaditajs = wp_users.user_login Left Join
n_sf_statusi On n_sf_statusi.id = tsales_funnel.Statuss
Left Join n_sf_fazes on tsales_funnel_mrecord.Product_faze = n_sf_fazes.id
Left Join
n_products On tsales_funnel_mrecord.Product_type = n_products.Product_Code
Left Join
(SELECT * FROM tsales_funnel_comments WHERE Comm_type = 4) as comm On tsales_funnel.ID = comm.Funnel_ID
Left Join
wp_users As wp_users02
On wp_users02.user_login = tsales_funnel_mrecord.Risk_acceptance
WHERE
tsales_funnel_clients.Tips_Galvenais = 1
";
$error = "Error: the query failed...
<pre style='width:700px;word-wrap:break-word;white-space:normal;'>$query</pre>";
$result = $wpdb->get_results( $query, ARRAY_A ) or wp_die( $error );
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'ID',
'B' => 'Darijuma_vaditajs',
'C' => 'Starpnieks',
'D' => 'OWCA',
'E' => 'Produkts',
'F' => 'Produkta_kods',
'G' => 'Saņēmšanas_datums',
'H' => 'Deadline',
'I' => 'Statuss',
'J' => 'Klienta_Regnr',
'K' => 'Klients',
'L' => 'Faze_date',
'M' => 'Faze',
'N' => 'Apdrošīnājuma_summa',
'O' => 'TRL_skaits',
'P' => 'Compensa_cena',
'Q' => 'Tirgus_cena',
'R' => 'Riska_parakstitajs',
'S' => 'Aizveršanas_komentārs'
);
// Build headers
foreach( $cell_definition as $column => $value )
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
// Build cells
while( $rowCount < count($result) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value ){
switch($column) {
case 'G';
case 'H';
$val = '=DATEVALUE("'.date('Y.m.d',strtotime($result[$rowCount][$value])).'")';
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
break;
case 'L';
$val = date('Y.m.d H:i:s',strtotime($result[$rowCount][$value]));
$objPHPExcel->getActiveSheet()->getStyle($column.$cell)
->getNumberFormat()
->setFormatCode("yyyy.mm.dd h:mm");
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
break;
default;
$val = $result[$rowCount][$value];
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
}
}
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="iPortal_Atskaite_'.date('Y-m-d_H.i.s', strtotime('+3 hour')).'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
I'm using switch for columns, where I need a different cell format.
Column G and H I need format 2015.10.05 (yyyy.mm.dd) And for column L 2015.10.05 12:03 (yyyy.mm.dd H:i).
Function getStyle() doesn't work, and returns the same value. If output as =datevalue, which is excel function, all is ok, but it doesn't work with time.
Also, if I press edit cell in excel and press enter, that date converts to normal date for excel and all works fine.
So, the problem is with output formatting. How can I define it? For other columns, for example for numbers, all is ok.

You need to convert your dates and date/times to an MS Excel serialized datetime stamp.... MS Excel does not automagically convert strings to dates for you, nor does simply setting a style change the actual value (a string in your case) that's stored in the cell in any way.
PHPExcel provides several different methods in the PHPExcel_Shared_Date class that will let you do these conversions.
$dto = new DateTime($result[$rowCount][$value]);
$dateVal = PHPExcel_Shared_Date::PHPToExcel($dto);
$objPHPExcel->getActiveSheet()->getStyle($column.$cell)
->getNumberFormat()
->setFormatCode("yyyy.mm.dd h:mm");
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $dateVal);

Related

How to get currency sign of cell-content using PhpSpreadsheet

I have cell content looks like "$ 1440" or "€ 970"
But on formula-field (after select cell) value looks like simple number "1440" or "970".
How can I get currency sign ($ or €) by using PhpSpreadsheet?
I tried code
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load('some.xlsx');
$worksheet = $spreadsheet->getActiveSheet();
$a = $worksheet->getStyle(10, 3)->getNumberFormat()->getFormatCode();
$b = $worksheet->getCellByColumnAndRow(10, 3)->getValue();
$c = $worksheet->getCellByColumnAndRow(10, 3)->getFormattedValue();
Got:
a - 'General' (string)
b - 1440 (integer)
c -'1440' (string)
Why is format "General" if it "Finance" actually?
You use $reader->setReadDataOnly(TRUE);.
That meant ignore formetting.
Set it to $reader->setReadDataOnly(FALSE);

PHPExcel toArray is changing date and time columns from XLSX format

I am using the excelToArray function found here: https://gist.github.com/calvinchoy/5821235
function excelToArray($filePath, $header = true) {
require_once("./PHPExcel/Classes/PHPExcel.php"));
//Create excel reader after determining the file type
$inputFileName = $filePath;
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Set read type to read cell data onl **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
//Get worksheet and built array with first row as header
$objWorksheet = $objPHPExcel->getActiveSheet();
//excel with first row header, use header as key
if($header){
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
}
else{
//excel sheet with no header
$namedDataArray = $objWorksheet->toArray(null,true,true,true);
}
return $namedDataArray;
}
I have two versions of a spreadsheet, one in CSV and one in Excel. Here they are:
CSV: https://drive.google.com/open?id=0B2GilRTNrTzKd3V3aEVET1NqSW8
XLSX: https://drive.google.com/open?id=0B2GilRTNrTzKdzJNZnh0cmhpa1E
When I upload the CSV using this function and var_dump the results I get
array (size=58)
0 =>
array (size=4)
'PD' => string '11/10/2016' (length=10)
'Pt' => string '9:12' (length=4)
'fd' => string '11/10/2017' (length=10)
'ft' => string '9:12' (length=4)
1 =>
array (size=4)...
But when I upload the XLSX I get:
array (size=58)
0 =>
array (size=5)
'PD' => float 42684
'Pt' => float 0.38333333333333
'fd' => float 43049
'ft' => float 0.38333333333333
'' => null
1 =>
array (size=5)
Notice that the PD goes from 11/10/2016 to 42684, and Pt from 9:12 to 0.38333...
What is causing the XLSX file to not be read in as it displays?
I have already read other stack questions, but I appear to be passing toArray the correct values. Not sure what I' missing...
MS Excel stores dates as a serialized timestamp, the number of days since 1t January 1900 (or 1st January 1904, depending on whether it is using the Windows or the Mac calendar). PHPExcel does likewise, so all dates/times are loaded to store in the spreadsheet object in exactly the way that MS Excel works with them.
So when you load a file with a human format date, it reads that as an MS Excel serialized timestamp. Ordinarily, it would also store the number format mask telling PHPExcel that this cell contains a timestamp value that shoud be formatted as a date, but you're telling PHPExcel's loader not to take this additional action by using $objReader->setReadDataOnly(true); which means store only the data, and not the formatting information.
Because PHPExcel desn't hve this additional formatting information, it cannot know that the cell contains something that should be dispayed as a date, so it can only dispay the serialized tiemstamp, which is really just a float.
In other words, don't do $objReader->setReadDataOnly(true); if you want dates to be treated as dates, or unless you want to do all the date handling yourself

How can I format some columns at date format when using PHPExcel script

I have a problem with date format when I using PHPExcel script
I have this code for generating xlsx file from wpdb Query:
<?php
# Load slim WP
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );
# http://phpexcel.codeplex.com/
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
global $wpdb;
$query = "Select
tsales_funnel.ID As ID,
wp_users.display_name As Darijuma_vaditajs,
tcportal_starpnieks.Cp_Name As Starpnieks,
tcportal_stucture.Cp_Name As OWCA,
n_products.Product_Nos As Produkts,
tsales_funnel_mrecord.Product_type as Produkta_kods,
tsales_funnel.Sanems_date as Saņēmšanas_datums,
tsales_funnel_mrecord.Deadline As Deadline,
n_sf_statusi.nosaukums_lv As Statuss,
tsales_funnel_clients.Reg_nr As Klienta_Regnr,
tfirmas_reg.name_in_quotes As Klients,
tsales_funnel_mrecord.Faze_date as Faze_date,
n_sf_fazes.nosaukums_lv As Faze,
tsales_funnel_mrecord.Summa As Apdrošīnājuma_summa,
tsales_funnel_mrecord.Vien_skaits As TRL_skaits,
tsales_funnel_mrecord.Compensa_cena,
tsales_funnel_mrecord.Tirgus_cena,
wp_users02.display_name As Riska_parakstitajs,
comm.Comment as Aizveršanas_komentārs
From
tsales_funnel Left Join
tsales_funnel_mrecord On tsales_funnel.ID = tsales_funnel_mrecord.Funnel_ID
Left Join
tcportal_starpnieks On tcportal_starpnieks.Cp_code = tsales_funnel.Starpnieks
Left Join
tcportal_stucture On tcportal_stucture.Cp_code = tsales_funnel.OWCA Left Join
tsales_funnel_clients On tsales_funnel_clients.Funnel_ID = tsales_funnel.ID
Left Join
tfirmas_reg On tfirmas_reg.regcode = tsales_funnel_clients.Reg_nr Left Join
wp_users On tsales_funnel.Darijuma_vaditajs = wp_users.user_login Left Join
n_sf_statusi On n_sf_statusi.id = tsales_funnel.Statuss
Left Join n_sf_fazes on tsales_funnel_mrecord.Product_faze = n_sf_fazes.id
Left Join
n_products On tsales_funnel_mrecord.Product_type = n_products.Product_Code
Left Join
(SELECT * FROM tsales_funnel_comments WHERE Comm_type = 4) as comm On tsales_funnel.ID = comm.Funnel_ID
Left Join
wp_users As wp_users02
On wp_users02.user_login = tsales_funnel_mrecord.Risk_acceptance
WHERE
tsales_funnel_clients.Tips_Galvenais = 1
";
$error = "Error: the query failed...
<pre style='width:700px;word-wrap:break-word;white-space:normal;'>$query</pre>";
$result = $wpdb->get_results( $query, ARRAY_A ) or wp_die( $error );
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'ID',
'B' => 'Darijuma_vaditajs',
'C' => 'Starpnieks',
'D' => 'OWCA',
'E' => 'Produkts',
'F' => 'Produkta_kods',
'G' => 'Saņēmšanas_datums',
'H' => 'Deadline',
'I' => 'Statuss',
'J' => 'Klienta_Regnr',
'K' => 'Klients',
'L' => 'Faze_date',
'M' => 'Faze',
'N' => 'Apdrošīnājuma_summa',
'O' => 'TRL_skaits',
'P' => 'Compensa_cena',
'Q' => 'Tirgus_cena',
'R' => 'Riska_parakstitajs',
'S' => 'Aizveršanas_komentārs'
);
// Build headers
foreach( $cell_definition as $column => $value )
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
// Build cells
while( $rowCount < count($result) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value )
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $result[$rowCount][$value]);
$rowCount++;
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="iPortal_Atskaite_'.date('Y-m-d_H.i.s', strtotime('+3 hour')).'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
I receive Date columns as YY-MM-DD, which is not supported by Excel.
But I need for:
'G' => 'Saņēmšanas_datums',
Format (YYYY.MM.DD) Like: 2015.12.31
And for:
'H' => 'Deadline', and 'L' => 'Faze_date',
I need date format (YYYY.MM.DD HH:MM:SS) Like 2015.12.31 15:31:22
How can I do that? I tried to find something in internet, but didn't find.
Take the date that you're getting from the database as YY-MM-DD, and convert it to a PHP DateTime object
$dateTimeObject = DateTime::createFromFormat('y-m-d', <date value from database row>, new DateTimeZone('UTC'));
Then convert that to an MS Excel serialised timestamp
$excelDate = PHPExcel_Shared_Date::PHPToExcel($dateTimeObject);
Finally, write that value to the cell, and set the format mask for that cell
$objPHPExcel->getActiveSheet()
->setCellValue(<cell address>, $excelDate);
$objPHPExcel->getActiveSheet()
->getStyle(<cell address>)
->getNumberFormat()
->setFormatCode('yyyy.mm.dd');
Similarly for date/time values

Values are not being added in Excel file using PHPExcel in yii

I'm trying to export data to Excel file using PHPExcel in yii. But I'm getting blank cells when I try to export data to excel file.
I'm able to add static values in the file such as column names.
$rowCount = 2;
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, "Sr. No");
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, "Suite Name");
this is the code in my controller action. I can see array values with that echo statement.
$i = 1;
$rowCount = 3;
foreach ($result as $row) {
$value = $row['suite_name'];
echo "<javascript type='text/javascript'>alert('$i, $rowCount, C$rowCount, D$rowCount ".$value."')</script>";
$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $i);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $value);
// Increment the Excel row counter
$rowCount++;
$i++;
}
instead of $value I tried directly with $row['suite_name'], that didn't worked either. Please, Any help will appreciated.
Try PHPExcel fromArray() method for saving array values to excel sheet.
Example
single dimensional array
$rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
$objPHPExcel->getActiveSheet()
->fromArray(
$rowArray, // The data to set
NULL, // Array values with this value will not be set
'C3' // Top left coordinate of the worksheet range where
// we want to set these values (default is A1)
);
Multi dimensional array
$arrayData = array(
array(NULL, 2010, 2011, 2012),
array('Q1', 12, 15, 21),
array('Q2', 56, 73, 86),
array('Q3', 52, 61, 69),
array('Q4', 30, 32, 0),
);
$objPHPExcel->getActiveSheet()
->fromArray(
$arrayData, // The data to set
NULL, // Array values with this value will not be set
'C3' // Top left coordinate of the worksheet range where
// we want to set these values (default is A1)
);

Download several excel files with one click

I have several php files which contain different queries to a postgresql database. There about sixteen of these files. Each of these files returns a different set of data based on the query within the file. After a query is made, you can download the file and the download is into an excel file.
My question is how can i trigger a download in php such that i can have just one link and upon clicking it, all these sixteen files are downloaded at once. I dont want to download each file on its on. Or better still i could have checkboxes and i select the files i would like to download. I hope my question is clear enough.
For example i have this file named export_a.php with this code
<?php require_once('connections/pgconn.php');
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "eastafrica_revenue_daily" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = pg_query("SELECT to_char (a.CALLDATE,'yyyymmdd') as transdate,
sum(a.alltaxcost::integer) AS revenue,
COUNT (DISTINCT a.IDENTIFIANT) AS distinct_callers,
a.zoneiddest as country_code,b.country
FROM cdr_data a, COUNTRY_CODES b
WHERE a.CALLSUBCLASS = '002'
AND a.CALLCLASS = '008'
and a.zoneiddest::integer > 0
AND SUBSTR (a.CALLEDNUMBER, 1, 2) NOT IN
('77', '78', '75', '70', '71', '41', '31', '39', '76','79')
and substr(a.zoneiddest,1,3) in ('254','255','211','257','250')
and trim(a.zoneiddest) = trim(b.country_code)
GROUP BY to_char (a.CALLDATE,'yyyymmdd') ,a.zoneiddest,b.country
ORDER BY 1") or die('Query failed!');
while(false !== ($row = pg_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>
Then i have another file say export_b.php with another query. When a link is clicked on a certain page say a.php where this query is made, it exports to excel.
My question is how can i trigger a download in php such that i can have just one link and upon clicking it, all these sixteen files are downloaded at once. I dont want to download each file on its on. Or better still i could have checkboxes and i select the files i would like to download.
If you want to download Excel files, why not download a single Excel file containing 16 worksheets (one for each of your datasets);
Alternatively zip all the files together, and download the zip

Categories