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
Related
This question already has answers here:
PHPExcel how to get column index from cell
(3 answers)
Closed 2 years ago.
I am using https://phpspreadsheet.readthedocs.io/en/latest/ phpspreadsheet to import files to database.I need to get the total number of columns in the uploaded excel before importing it to database.
I found getHighestDataColumn() which returns the highest coulmn as alphabets.
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($fileName);
$worksheet = $spreadsheet->setActiveSheetIndex(0);
$high=$spreadsheet->setActiveSheetIndex(0)->getHighestColumn();
dump($high);
die;
which gives output as I
Is there any way to get it as numbers ..??
If you only have A-Z you can convert the chars to ascii and get their int value using ord.
// Get ascii offset for alphabet
$start = ord("A");
$current = "I";
// Calculate char position from offset A
echo ord($current) - $start;
Found the solution as
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($fileName);
$worksheet = $spreadsheet->setActiveSheetIndex(0);
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
dump($highestColumnIndex);
die;
This will output the index of highestColumn ..
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 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);
I am using PHPExcel to save a multidimensional array data in a xls file
This is my code:
$arr = array(
array("01", "02", "03"),
array("04", "05", "06"),
);
// include PHPExcel library
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->fromArray($arr);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save("file.xls");
My problem is that starting nulls are removed in my xls file. For example is saved not as 01, but as 1.
How to solve this problem?
If you want a string with a numeric value to retain leading zeroes, then you have two choices:
Write it as a string using
$objPHPExcel->getActiveSheet()->getCell('A1')
->setValueExplicit(
'01',
PHPExcel_Cell_DataType::TYPE_STRING
);
(PHPExcel_Cell_DataType::TYPE_STRING is the default, so you don't actually have to specify that argument)
or allow it to be written as a number, and then set a format mask to display it with leading zeroes
$objPHPExcel->getActiveSheet()->getStyle('A1')
->getNumberFormat()
->setFormatCode("00");
EDIT
You can apply a style to a range of cells, not just to individual cells
$arr = array(
array("01", "02", "03"),
array("04", "05", "06"),
);
// include PHPExcel library
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->fromArray($arr);
$objPHPExcel->getActiveSheet()->getStyle('A1:C2')
->getNumberFormat()
->setFormatCode("00");
There seems to be a solution on the forum:
http://phpexcel.codeplex.com/discussions/31240
you need to set the row's attribute like this
$objPHPExcel->getActiveSheet()->getStyle('A0')->getNumberFormat()->setFormatCode("#");
but i don't know what format you need ,just look for the mannul
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;