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
Related
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.
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'm having problems outputting an excel with its date object. I'm using PHPExcel on Symfony. I performed an SQL that grabs data from the database in my Symfony controller. Then I did a for loop to iterate through each rows of data. However when I added in the value of a date, it gives me an error:
FatalErrorException: Error: Cannot use object of type DateTime as array in ...\Symfony\vendor\phpoffice\phpexcel\Classes\PHPExcel\Cell\DefaultValueBinder.php line 86
Here is my code:
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
// ..etc
for($results as $result) {
// codes..
->setCellValue('H'.$i, $result['date'])
}
It's not allowing me to output the excel because of this. Should I be converting it to a string?
I found the solution through looping through the cell with the date values and setting it as date by number format:
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
// ..etc
$i = 3;
for($results as $result) {
$excel->getActiveSheet()->getStyle('H'.$i)
->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
$date = \PHPExcel_Shared_Date::PHPToExcel($result['date']);
// codes..
->setCellValue('H'.$i, $result['date'])
}
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
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()