I'd like some help to solve a problem with the PHP Excel library to import a cell data.
In my script I need to check if a cell is formatted as a date, using "PHPExcel_Shared_Date::isDateTime".
For some date cells, the format is flagged by MS Excel like this :
"Date formats that begin with an asterisk (*) respond to changes in regional date and time settings that are specified for the Operating System."
And for thoses cells, the test PHPExcel_Shared_Date::isDateTime fails, I obtain this :
$reader = PHPExcel_IOFactory::createReaderForFile($filepath);
$objexcel = $reader->load($filepath);
$cell = $objexcel->getSheet()->getCell('A2');
var_dump(PHPExcel_Shared_Date::isDateTime($cell)); // return false
echo $cell->getFormattedValue(); // return timestamp : 43466
When I convert my xlsx file in xls file or when I give another date format to my cell, it works, I obtain this :
$reader = PHPExcel_IOFactory::createReaderForFile($filepath);
$objexcel = $reader->load($filepath);
$cell = $objexcel->getSheet()->getCell('A2');
var_dump(PHPExcel_Shared_Date::isDateTime($cell)); // return true
echo $cell->getFormattedValue(); // return 2019-01-01
The "setReadDataOnly" is still at false for my reader.
Does someone has any idea to fix it ?
(I precise that i'm in France, and we write dates at format 'd/m/Y')
Thanks in advance for helping me.
Related
I have xlsx tables and I use PhpSpreadsheet to parse them. One Column is date format. The problem is that PhpSpreadsheet returns the values from date-formatted cells in an unspecified format:
2-Jan-19 (in Excel) and 43467 (After Exporting)
And I need to save entire tables exactly as they look like in Excel Format, like "2-Jan-19" not "43467"
I've been read
Retrieve Date From Table Cell,
But it can't solve my problem
Below is the code I have right now:
$spreadsheet = $reader->load($_FILES['berkas_excel']['tmp_name']);
$sheetData = $spreadsheet->getSheet(0)->toArray();
echo count($sheetData);
for($i = 3;$i < count($sheetData) ;$i++)
{
$kode = $sheetData[$i]['0'];
$tgl = $sheetData[$i]['1']; //This is where the Date Column
$shift_rec = $sheetData[$i]['2'];
$grup = $sheetData[$i]['3'];
$pekan = $sheetData[$i]['4'];
$bulan = $sheetData[$i]['5'];
}
I hope somebody can help me to get "2-Jan-19" as the result, so I can insert it into my DB after that,
Thanks to anyone who willing to answer/help my problem right now
I have the following Excel file:
I read it in by looping over every cell and getting the value with getCell(...)->getValue():
$highestColumnAsLetters = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); //e.g. 'AK'
$highestRowNumber = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$highestColumnAsLetters++;
for ($row = 1; $row < $highestRowNumber + 1; $row++) {
$dataset = array();
for ($columnAsLetters = 'A'; $columnAsLetters != $highestColumnAsLetters; $columnAsLetters++) {
$dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($columnAsLetters.$row)->getValue();
if ($row == 1)
{
$this->column_names[] = $columnAsLetters;
}
}
$this->datasets[] = $dataset;
}
However, although it reads in the data fine, it reads in the calculations literally:
I understand from discussions like this one that I can use getCalculatedValue() for calculated cells.
The problem is that in the Excel sheets I am importing, I do not know beforehand which cells are calculated and which are not.
Is there a way for me to read in the value of a cell in a way that automatically gets the value if it has a simple value and gets the result of the calculation if it is a calculation?
Answer:
It turns out that getCalculatedValue() works for all cells, makes me wonder why this isn't the default for getValue() since I would think one would usually want the value of the calculations instead of the equations themselves, in any case this works:
...->getCell($columnAsLetters.$row)->getCalculatedValue();
getCalculatedValue() seems to work for all cells, see above
If you are unsure about the content of a cell (value or formula included),
I recommend you to primarily do a check if the cell has a formula and then copy - paste accordingly. getOldCalculatedValue() is very helpful in this case. Here is an example of that:
$code = $sheet->getCell('A'.$y)->getValue();
if(strstr($code,'=')==true)
{
$code = $sheet->getCell('A'.$y)->getOldCalculatedValue();
}
$objPHPExcel4->setActiveSheetIndex(0)
->setCellValue('A'.$l, $code);
For large data sets, getCalculatedValue() function is really cumbersome and lots of memory will be required to perform correctly.
Looks like getCalculatedValue() is deprecated. Try using getFormattedValue() instead.
getCalculatedValue() seems to do the right job you wanted. It will return the correct value if the cell contains FBV ( formula based value ). If not then the normal value will be returned instead.
getCalculatedValue
seems to work for all cells
$sheets = $spreadsheet->getAllSheets();
$priceCasegetCellByColumnAndRow = $sheet->getCellByColumnAndRow(14, ($key))->getCalculatedValue()
$priceCasegetCell = $sheet->getCell('O' . $key)->getCalculatedValue();
I have never imported an excel file in PHP so this is just a stab in the dark.
Why not check the first character in the cell for an "="
If true getCalculatedValue()
if not getCell()
I am using excel/reader.php to read the CSV file and get the data.
The date field in CSV have value: 20/10/2014
Customer Name Date
Lorem Spem 20/10/14
and when I print this after reading the CSV using PHP:
$file_name = $_FILES['file']['tmp_name'];
$library_path = getcwd().'/application/libraries/excel/reader.php';
require_once $library_path;
$excel = new Spreadsheet_Excel_Reader();
$excel->setOutputEncoding('CP1251');
$status = $excel->read($file_name);
$totalSheets = count($excel->sheets);
for($sheetCount = 0 ; $sheetCount < $totalSheets ; $sheetCount++)
{
$excel_data = $excel->sheets[$sheetCount]['cells'];
$totalRows = $excel->sheets[$sheetCount]['numRows'];
print_r($excel_data);
}
It gives the result: 21/10/2014
Array ( [1] => Lorem Spem [2] => 21/10/2014 )
I don't know why it add one day to the date from CSV.
I have found the code is correct: it was giving one day added to the date from Excel sheet on Local Host only.
When I have uploaded this code to the Live Server, it is giving correct date.
I think this is Time Zone issue again. As the CSV which I tried to read was made in Canada time zone, and I tried to read in India time zone, so the error of date shows.
But when I uploaded the code to the live server of Canada, then it starts giving the correct date from the Excel Sheet.
I use PHPExcel lib for read the excel file in Codeigniter project. It is not read some cells with calculation. It show as #VALUE! But some values with calculation is reading in same excel sheet. Whats wrong with those cells?
Cells with have following calculation is not reading
=+D109*1000
=+B16/B13
=+D23/$D$109
Cells with have following calculation is reading
=+B10-B11
=+C10-C11
But all cells are reading for some excel sheet. This issue come with xlsx format
This is my code
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$this->excel = $objReader->load($path);
$this->excel->setActiveSheetIndex($sheet);
$data = $this->excel->getActiveSheet()->toArray(null, true, true, true);
print_r($data);
I check with google. getCalculatedValue() should use for read calculated values. But i can't use it one by one. Is it has a method to read all sheet as array?
How ever i checked some cells with following way
$this->excel->getActiveSheet()->getCell('B18')->getCalculatedValue() // return #VALUE!
$this->excel->getActiveSheet()->getCell('B18')->getOldCalculatedValue() //return 0.4211
How i use old calculated value using toArray?
Finally I get old getOldCalculatedValue using loop.
$data = $this->excel->getActiveSheet()->toArray(null, true, true, true);
//This code add for some calculated cells were not reading in xlsx format
foreach ($data as $no => $row) {
foreach ($row as $key => $value) {
if (isset($value) && $value == '#VALUE!') {
$data[$no][$key] = $this->excel->getActiveSheet()->getCell($key.$no)->getOldCalculatedValue();
}
}
}
I am using an existing Excel file, with the first row containing plain text, to be used later as template. I then changed a few of the column formats to currency, accounting, date...e.t.c. Now I am loading in this file in phpExcel and populating data from my database to this file and saving it with a new name. But on the saved file, all cells in the newly created rows seem to be marked general, though the original plain text row still seems to have the correct format assigned.
My Code:
$xl_tmplt = ((isset($_REQUEST['excel_template']) && $_REQUEST['excel_template'] != "")
? $_REQUEST['excel_template']
: "report_tab1.xlsx");
require_once 'includes/classes/PHPExcel/PHPExcel.php';
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array('memoryCacheSize' => '8MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
$tmp_workbook = PHPExcel_IOFactory::load($tmp_folder_path . '/templates/' . $xl_tmplt);
$tmp_workbook->setActiveSheetIndex(0);
$sheet = $tmp_workbook->getActiveSheet();
$sheet->fromArray($arr, '', 'A2');
$objWriter = PHPExcel_IOFactory::createWriter($tmp_workbook, 'Excel2007');
$objWriter->save($tmp_folder_path . "output/$filename");
$result['type'] = "success";
$result['msg'] = "The file was successfully created.";
Any idea how I can load in an excel file with predefined column formats and use it to generate a new excel? Or change/set the format of a column or cell range during generation?
PS: I am not too good with excel so I might have set the column format in the wrong way. basically I clicked on the column letter which selects the column, and then changed the format in the dropdown above. If this is wrong, please let me know.
Please check below link for example of setting Row and Cell style
http://phpexcel.codeplex.com/workitem/7333
UPDATE:
For formatting Numbers, Text, Date and Currency, please check below link
PHPExcel Formatting