laravel-phpexcel , getCalculatedValue() returns int 0 - php

I'v been struggling for days now with this issue.
I have an xls file, containing multiple sheets, with functions on it.
What i'm trying to do is to insert values at the first sheet, and then retrieve the result from the second one, but the result i'm getting is 0.
This is the code i'v written
$fileType = 'Excel5';
$fileName = storage_path().'/penssion_simulator_file/test2.xls';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(true);
echo "Start loading file:</br>";
echo date('H:i:s d/m/Y')."</br>";
$objPHPExcel = $objReader->load($fileName);
echo "End of loading file:</br>";
echo date('H:i:s d/m/Y')."</br>";
PHPExcel_Calculation::getInstance($objPHPExcel)->disableCalculationCache();
PHPExcel_Calculation::getInstance($objPHPExcel)->clearCalculationCache();
echo "Start setting values to file:</br>";
echo date('H:i:s d/m/Y')."</br>";
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B7', (string)date('d/m/Y'))
->setCellValue('B8', (string)'30/05/1984')
->setCellValue('B9', (string)'01/05/2013')
->setCellValue('B10', (integer)20000)
->setCellValue('B11', (string)'ללא בן זוג וילדים (לצורכי ביטוח)')
->setCellValue('B12', (float)5.5)
->setCellValue('B13', (float)6.0)
->setCellValue('B14', (float)8.33)
->setCellValue('B15', '-')
->setCellValue('B16', (string)'גבר')
->setCellValue('B17', (integer)0)
->setCellValue('B18', (integer)0)
->setCellValue('B19', (string)'עתיר חיסכון')
->setCellValue('B20', (float)6.0)
->setCellValue('B21', (float)0.25)
->setCellValue('B22', (integer)67)
->setCellValue('B23', (string)'כן')
->setCellValue('B24', (string)'לא');
echo "End of setting values to file:</br>";
echo date('H:i:s d/m/Y')."</br>";
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
echo "Value of cell B6 on sheet 1: ".($objWorksheet->getCell('B6')->getCalculatedValue())."</br>";
// $value = $this->getCellValue($objWorksheet,'B3');
// echo "</br>This is the value og cell B3: ".$value."</br>";
// PHPExcel_Calculation::getInstance()->writeDebugLog = true;
// $this->testFormula($objWorksheet,'B3');
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
echo "Value of cell B7 on sheet 0: ".($objPHPExcel->getActiveSheet()->getCell('B7')->getValue())."</br>";
echo date('H:i:s d/m/Y')."</br>";
// Change the file
die('FIN');
And those are the outputs that i'm printing:
Start loading file:
09:03:27 28/01/2015.
End of loading file:
09:04:26 28/01/2015.
Start setting values to file:
09:04:26 28/01/2015.
End of setting values to file:
09:04:26 28/01/2015
Value of cell B6 on sheet 1: 0
Value of cell B7 on sheet 0: 28/01/2015
09:04:30 28/01/2015
FIN
I'm using laravel as i mentioned at the header of this post, and the laravel-phpexcel package.
Appreciate your help!

Related

PHPExcel find last row of data starting from a specific cell

i have a php script that read data from excel file starting from cell B6. However. I would like the php to be able to read data from B6 until the last row of data which in this case is cell D7.
I try searching online for answer and all i get is this $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
Can anyone help?
Below is my php script code:
require_once 'Classes/PHPExcel.php';
$path = 'import/Attachment F - Visitor or Supplier Request Template.xlsx';
$reader = PHPExcel_IOFactory::createReaderForFile($path);
$excel_obj = $reader->load($path);
$worksheet = $excel_obj->getSheet('0');
for($row=6;$row<=14;$row++){
$category = $worksheet->getCell('B'.$row)->getValue();
if($category!=''){
$uen = $worksheet->getCell('C'.$row)->getValue();
$company = $worksheet->getCell('D'.$row)->getValue();
echo $category." ".$uen." ".$company."<br/>";
}
}

Read excel sheet containing merged cells using PHPExcel

I want to read an excel sheet completely and using AJAX send each row to another page for processing. So I have used the following code for converting the excel sheet data into JSON array(Reference PHPExcel example provided in Library):
<?php
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Asia/Kolkata');
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel-1.8/Classes/');
require_once 'PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($fileLocation);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly("SHEETNAME");
$objPHPExcel = $objReader->load($fileLocation);
$data = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
?>
Here $filelocation is the location of the uploaded file which is to be read for sending the rows individually using AJAX to another page.
I am using $data in javascript as
DataToBeUploaded=<?php echo json_encode($data);?>;
But the excel sheet contains some merged cells so PHPExcel is not able to read the values in these merged cells. Hence values in these cells are read as NULL.
Is there a way where I can use the merged cells' upper left cell value for all of the subsequent cells? (Actually in my case cells are merged vertically only)
Eg.
I have (Assume rows are numbered from 1 and columns from A)
Here PHPExcel reads this as:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]=''
$data[2][B]='456'
$data[3][A]=''
$data[3][B]='789'
I want the snippet to result in these values:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]='abc'
$data[2][B]='456'
$data[3][A]='abc'
$data[3][B]='789'
Referring to https://github.com/PHPOffice/PHPExcel/issues/643
I have written the following snippet:
$referenceRow=array();
for ( $row = 2; $row <= $noOfBooks; $row++ ){
for ( $col = 0; $col < 7; $col++ ){
if (!$objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isInMergeRange() || $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isMergeRangeValueCell()) {
// Cell is not merged cell
$data[$row][$col] = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getCalculatedValue();
$referenceRow[$col]=$data[$row][$col];
//This will store the value of cell in $referenceRow so that if the next row is merged then it will use this value for the attribute
} else {
// Cell is part of a merge-range
$data[$row][$col]=$referenceRow[$col];
//The value stored for this column in $referenceRow in one of the previous iterations is the value of the merged cell
}
}
}
This will give the result exactly as required

Issue using formula on PHPExcel (Excel2007)

When I try to set the value of an cell with a formula, e.g.: setCellValue('C1', '=A1+B1'), the generated file don't have the calculated value for the cells.
I have the following script:
<?php
require_once '../vendor/autoload.php';
date_default_timezone_set('America/Sao_Paulo');
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 5)
->setCellValue('B1', 10)
->setCellValue('C1', '=A1+B1');
echo $objPHPExcel->getActiveSheet()->getCell('C1')->getCalculatedValue() . PHP_EOL;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('a.xlsx');
When I open a.xlsx with libreoffice, the cell C1 shows the string "0". The odd thing is that when I click the cell it actually shows "=A1+B1", but not the final result.
How do I get PHPExcel to work with formulas properly?
I had the same problem with LibreOffice 5.0.5.2.
Changing the following option in LibreOffice Calc worked for me:
Go to Tools/Options.../LibreOffice Calc/Formula
In section "Recalculation on file load", "Excel 2007 and newer", change the value to "Always recalculate"
Found on
https://ask.libreoffice.org/en/question/12165/calc-auto-recalc-does-not-work/

PHPExcel Make first row bold

I am trying to make cells in first row are bold.
This is the method I have created for that purpose.
function ExportToExcel($tittles,$excel_name)
{
$objPHPExcel = new PHPExcel();
$objRichText = new PHPExcel_RichText();
// Set properties
$objPHPExcel->getProperties()->setCreator("SAMPLE1");
$objPHPExcel->getProperties()->setLastModifiedBy("SAMPLE1");
$objPHPExcel->getProperties()->setTitle("SAMPLE1");
$objPHPExcel->getProperties()->setSubject("SAMPLE1");
$objPHPExcel->getProperties()->setDescription("SAMPLE1");
// Add some data
$objPHPExcel->setActiveSheetIndex(0);
$letters = range('A','Z');
$count =0;
$cell_name="";
foreach($tittles as $tittle)
{
$cell_name = $letters[$count]."1";
$count++;
$value = $tittle;
$objPHPExcel->getActiveSheet()->SetCellValue($cell_name, $value);
// Make bold cells
$objPHPExcel->getActiveSheet()->getStyle($cell_name)->getFont()->setBold(true);
}
// Save Excel 2007 file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$objWriter->save($excel_name.".xlsx");
}
The problem is in output excel file the cells are not bold.
Try this for range of cells:
$from = "A1"; // or any value
$to = "B5"; // or any value
$objPHPExcel->getActiveSheet()->getStyle("$from:$to")->getFont()->setBold( true );
or single cell
$cell_name = "A1";
$objPHPExcel->getActiveSheet()->getStyle( $cell_name )->getFont()->setBold( true );
Try this
$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);
That way you get the complete first row
Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:
$header = array(
'Header 1',
'Header 2'
);
$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);
Use this:
$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);
These are some tips to make your cells Bold, Big font, Italic
Let's say I have columns from A to L
A1 - is your starting cell
L1 - is your last cell
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setItalic(true);
$objPHPExcel->getActiveSheet()->getStyle("A1:".$objPHPExcel->getActiveSheet()->getHighestDataColumn()."1")->getFont()->setBold(true);
I found this to be a working solution, you can replace the two instances of 1 with the row number. The HighestDataColumn function returns for example C or Z, it gives you the last/highest column that's in the sheet containing any data. There is also getHighestColumn(), that one would include cells that are empty but have styling or are part of other functionality.
This iterates through a variable number of columns of a particular row, which in this case is the 1st row:
$rownumber = 1;
$row = $this->objPHPExcel->getActiveSheet()->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$cell->getStyle()->getFont()->setBold(true);
}
The simple way to make bold headers:
$row = 1;
foreach($tittles as $index => $tittle) {
$worksheet->getStyleByColumnAndRow($index + 1, $row)->getFont()->setBold(true);
$worksheet->setCellValueByColumnAndRow($index + 1, $row, $tittle);
}
Try this
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->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");
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValue('A1', 'No');
$sheet->setCellValue('B1', 'Job ID');
$sheet->setCellValue('C1', 'Job completed Date');
$sheet->setCellValue('D1', 'Job Archived Date');
$styleArray = array(
'font' => array(
'bold' => true
)
);
$sheet->getStyle('A1')->applyFromArray($styleArray);
$sheet->getStyle('B1')->applyFromArray($styleArray);
$sheet->getStyle('C1')->applyFromArray($styleArray);
$sheet->getStyle('D1')->applyFromArray($styleArray);
$sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)
You can try
$objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);

php_excel07- How to make grow the height of cell based on cell data(xls)

In my application i need to export to xls file in a predefined format.
so I just integrated php_excel2007. I am using one template with a predefined format.
The problem here is the cell data may change dynamically. if data is much bigger than cell height then data is collapsing.
So is ther anyway to increase the height of cell based on content of the cell(in XLX not xlsx)?
The only way is as described in this answer to your previous question on this topic: setting the row height to autofit, and the cell alignment to wrap. This should work the same way, whether you use the Excel5 Writer or the Excel2007 Writer.
$objPHPExcel = new PHPExcel();
// Set some long string values in some cells
$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("This is a large block of text,\ncomprising several lines,\nthat will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A2')->setValue("This is a large block of text that will NOT be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('B1')->setValue("This is another large block of text without any line breaks, that will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A3')->setValue("This is another large block of text,\ncomprising several lines,\nthat will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A4')->setValue("This is another large block of text without any line breaks, that will be set to autofit but not wrap.");
// Fix the column width to a reasonable size
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
// Set text wrap for cells A1 and B1. This forces the text to wrap, but doesn't adjust the height of the row
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setWrapText(true);
// Set rows 1, 3 and 4 to autofit the height to the size of text
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getRowDimension(4)->setRowHeight(-1);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('testAutoHeight.xls');
EDIT
Added comments to the code sample to explain what each called method actually does
setRowHeight to -1 for make auto height (based on cell data)
// auto-size on row 1
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
<?php
error_reporting(E_ALL);
require_once ROOT.'/PHPExcel.php';
function down($details)
{
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load(ROOT."/templates/project_report1.xls");
// Set properties
$p_i=5;$alpa="B";$row_no=5;$mil="";$d_cel="B";
$objPHPExcel->setActiveSheetIndex()
->setCellValue('K1', $details['report_details']['cur_time']);
$objPHPExcel->setActiveSheetIndex()
->setCellValue('C2', 'REPORT START DATE:'.$details['report_details']['start_date'])
->setCellValue('H2', $details['report_details']['details'])
->setCellValue('C3', 'SHOWING:'.$details['report_details']['showing']);
foreach($details as $p_name=>$date){
//thisis to display date at the top
foreach($date as $p1=>$m_name1){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($d_cel.'4', $p1);$d_cel++;//to display date in the top
}
break;
}
foreach($details as $p_name=>$date){
if($p_name=="report_details")break;
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$p_i, $p_name);
$objPHPExcel->getActiveSheet(0)->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('A5'), 'A'.$p_i );
$objPHPExcel->setActiveSheetIndex(0)->getStyle('A'.$p_i)->getAlignment()->setWrapText(true);
foreach($date as $p=>$m_name){
$mil=$tic=$st=" ";
foreach($m_name as $name=>$val){
if($name=="milestone")
foreach($val as $in_det=>$det){
if($det && isset($det['start_date']))
$mil.=$det['name']."\n".$det['start_date']."\n";
else
$mil.=$det['name'];
}
if($name=="ticket")
foreach($val as $in_det=>$det){
if($det)
$tic.=$det['name']." ".$det['start_date']."\n";
}
if($name=="task")
foreach($val as $in_det=>$det){
if($det)
$st.=$det['name']." ".$det['start_date']."\n";
}
}
$summary=$mil.$tic.$st;
$objPHPExcel->getActiveSheet(0)->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('B5'), $alpa.$p_i );
$objPHPExcel->getActiveSheet(0)->getRowDimension($p_i)->setRowHeight();
$objPHPExcel->getActiveSheet(0)->getStyle('A'.$p_i.':'.'M'.$p_i)->getAlignment()->setWrapText(true);
$objPHPExcel->setActiveSheetIndex(0)->getStyle($alpa.$p_i)->getFont()->setSize(5);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($alpa.$p_i, $summary);
$alpa++;
}
$alpa="B";
$p_i++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Report');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="project_report.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
?>

Categories