Issue with Countifs in PHPExcel when generating a PDF - php

I have a problem with PHPExcel and can’t seem to find the solution to fix it.
I wrote a script based on the basic examples provided in the PHPExcel documentation to create a PDF file out of a XLSX file my code looks like this:
$inputfile = “test.xlsx”;
$objReader = PHPExcel_IOFactory::createReaderForFile($inputfile);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputfile);
[…]
$objWriter = new PHPExcel_Writer_PDF($objPHPExcel);
$objWriter->setSheetIndex(0);
$objWriter->setPreCalculateFormulas(true);
$objWriter->save("test.pdf");
The PDF Writer Library I am using is DomPDF.
Now the problem is that this code above will return me an Error when I try to create a PDF with this specific file I am working on.
Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with message 'Sheet!C5 -> Formula Error: Wrong number of arguments for COUNTIFS() function: 4 given, 2 expected' in D:\xampp\htdocs\doc\phpxls\Classes\PHPExcel\Cell.php:300 Stack trace: #0 D:\xampp\htdocs\doc\phpxls\Classes\PHPExcel\Writer\HTML.php(1174): PHPExcel_Cell->getCalculatedValue() #1 D:\xampp\htdocs\doc\phpxls\Classes\PHPExcel\Writer\HTML.php(436): PHPExcel_Writer_HTML->_generateRow(Object(PHPExcel_Worksheet), Array, 4) #2 D:\xampp\htdocs\doc\phpxls\Classes\PHPExcel\Writer\PDF\DomPDF.php(109): PHPExcel_Writer_HTML->generateSheetData() #3 [internal function]: PHPExcel_Writer_PDF_DomPDF->save('testing.pdf') #4 D:\xampp\htdocs\doc\phpxls\Classes\PHPExcel\Writer\PDF.php(87): call_user_func_array(Array, Array) #5 D:\xampp\htdocs\doc\interface\xls2pdf_2.php(59): PHPExcel_Writer_PDF->__call('save', Array) #6 D:\xampp\htdocs\doc\interface\xls2pdf_2.php(59): PHPExcel_Writer_PDF->save('testing.pdf') #7 {main} thrown in D:\xampp\htdocs\doc\phpxls\Classes\PHPExcel\Cell.php on line 300
You can see it’s something about “COUNTIFS()” my assumption was that setReadDataOnly(true) would only give me the values of the cells and ignore the formulas after reading the documentation I realize this is not true. Is there a way to only get the values of the Cell without formula?
If I set $objWriter->setPreCalculateFormulas(false);
It will work without error but the returned PDF file will show the formulas instead of the calculated values in the cells (obviously)
Is there any way to make this work like I intended it to? Just reading / writing the values and ignoring the formula?
My suspicion is that the error has something to do with the separator in the formula which in the local format I am using (German) is semicolon but in the US/Standard format is comma so the formula looks like this in the original file
=ZÄHLENWENNS(Migration_LSA!$AR$2:$AR$121;">=1/4/2014";Migration_LSA!$AR$2:$AR$121;"<=30/4/2014")
And in theory should look like this in PHPExcel
=COUNTIFS(Migration_LSA!$AR$2:$AR$121,">=1/4/2014",Migration_LSA!$AR$2:$AR$121,"<=30/4/2014")

The problem isn't to do with the separator at all, this is only an issue if you were inserting the formula into PHPExcel directly as
=ZÄHLENWENNS(Migration_LSA!$AR$2:$AR$121;">=1/4/2014";Migration_LSA!$AR$2:$AR$121;"<=30/4/2014")
when you would need to set the locale, and use the translate methods before inserting it. Internally (in both PHPExcel and MS Excel) formulae are represented in their English/US format. The MS Excel GUI hides this from you with automatic translation on insert/display.
At the moment, the COUNTIFS() formula in PHPExcel only works with a single range/criteria pair.
You can work round this by splitting your multiple range/criteria pairs into single range/criteria pairs and adding those together, so:
=COUNTIFS(Migration_LSA!$AR$2:$AR$121,">=1/4/2014") +
COUNTIFS(Migration_LSA!$AR$2:$AR$121,"<=30/4/2014")
setReadDataOnly(true) tells the PHPExcel Reader only to read the cell content, not to read styles, format masks, print settings, conditional styles, etc... but formulae are still cell content

Related

PHPExcel: problem while writing cell data type issue

I have PHP code to export the data to excel. Used PHPExcel library for the same.
PHPExcel library Version 1.7.6
We encountered a problem while writing the following value ==PD==[HW]RECEIVING CRC ERRORS
When I open the Excel manually and set the cell data type as TEXT it is accepting this value.
But while trying to generate the excel using PHPExcel library, getting an error as below exception 'Exception' with message 'L14 -> Formula Error: Unexpected operator '=''
I tried to solve this issue by setting the data type of the cell as STRING, but no luck... Tried below ways to set the cell data type...
#first try
$activeSheet->setCellValueExplicit($symptomColumn.$rowCount, $val, PHPExcel_Cell_DataType::TYPE_STRING);
#second try
$activeSheet->getCell($symptomColumn.$rowCount)->setValueExplicit($val, PHPExcel_Cell_DataType::TYPE_STRING);
#third try
$activeSheet->getCell($symptomColumn.$rowCount)->setDataType(PHPExcel_Cell_DataType::TYPE_STRING);
#fourth try
$activeSheet->getStyle($symptomColumn.$rowCount)
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
#fifth try
$activeSheet->getStyle($symptomColumn.$rowCount)
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
Can anyone please help me to resolve the issue while writing the text "==PD==[HW]RECEIVING CRC ERRORS" to the cell while creating an excel using PHPExcel library?
Thanks in Advance...
If PHPExcel encounters a cell where the first character of content is an =, then it considers that cell to contain an Excel formula, and will try to evaluate it as such. If it isn't actually a formula, then it will throw an exception like this.
There is no simple solution in PHPExcel, other than to suggest that you add a leading space (or other character) before the =. PHPExcel is no longer a supported library, and this bug will not be fixed (especially not in the older version that you are running).
The latest master branch of the successor library PHPSpreadsheet does contain a fix for this, allowing you to set the style of the cell to quoted text. This will identify that this is not a formula to the calculation engine, and is similar to what you are recommended to do in MS Excel itself.
$workSheet->setCellValue('A2', "==PD==[HW]RECEIVING CRC ERRORS");
$workSheet->getCell('A2')->getStyle()->setQuotePrefix(true);

PHPExcel Multiple worksheet formula returning PHPExcel_Calculation_Exception

Goodevening,
I'm using the PHPExcel Library to populate an existing Excel sheet with some data, and show the result of the calculated value on a webpage.
I've got a couple of formulas that look like this:
=IF(OR($B$7=$A$17;$B$8=$A$17;$B$9=$A$17);"";B9)
=IF(B12<=B14;IF(B12=A17;A17;VLOOKUP(CEILING(B12;1);'Motor selection'!$1:$1048576;2;FALSE));A17)
I get the following error when I try to get the calculated value of 'B9' for example:
Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with message 'Pump selection!D7 -> Pump selection!B9 -> Formula Error: An unexpected error occured' in includes/PHPExcel/Classes/PHPExcel/Cell.php:291
I'm using the following PHP code, which is pretty standard.
$objType = PHPExcel_IOFactory::identify($file);
$objReader = PHPExcel_IOFactory::createReader($objType);
$objPHPExcel = $objReader->load($file);
// Populate values
$objPHPExcel->getActiveSheet()->setCellValue('B4', 100)
->setCellValue('B5', 75);
// Motor
$motor = $objPHPExcel->getActiveSheet()->getCell('B9')->getFormattedValue();
As I am not an Excel expert (a client sent me this) I have no clue what is going wrong or how to fix this. All I know is that the formulae in the sheet itself are working fine when I open it in Excel.
Would love to know if someone can assist me on this. I can share the complete Excel file if that's necessary.
Thanks in advance,
Kevin
Edit: I've read that the issues might have something to do with the dollar signs in the formula, and I've already tried escaping them with \$ but that doesn't seem to make a difference.
Edit2: The file can be found here. Idea is that B4 and B5 of the first sheet get populated with form data, and the result will be in D7:H7.

Prevent PHPExcel to calculate values when writing to file

When writing my data in an Excel file with class PHPExcel.
This is happening when the writer works, not when adding data to the cells $this->sheet->setCellValue()
Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with message 'Adressen!AF20955 -> Formula Error: Unexpected operator '>'' in \Cell.php:300 Stack trace:
#0 \PHPExcel\Worksheet.php(754): PHPExcel_Cell->getCalculatedValue()
#1 \PHPExcel\Writer\Excel2007\Worksheet.php(373): PHPExcel_Worksheet->calculateColumnWidths()
#2 \PHPExcel\Writer\Excel2007\Worksheet.php(80): PHPExcel_Writer_Excel2007_Worksheet->_writeCols(Object(PHPExcel_Shared_XMLWriter), Object(PHPExcel_Worksheet))
#3 \PHPExcel\Writer\Excel2007.php(304): PHPExcel_Writer_Excel2007_Worksheet->writeWorksheet(Object(PHPExcel_Worksheet), Array, false)
#4 \excel.php(131): PHPExcel_Writer_Excel2007->save('...')
#5 \excel. in \PHPExcel\Cell.php on line 300
I never use the function PHPExcel_Cell->getCalculatedValue() writing to my Excel but only $this->sheet->setCellValue('A1', $value).
I don't need to calculate any formula in my Excel file. Just exporting DB2 data to this file.
It is obviously possible that $value contains formula characters like = + - > < (as the cell AF20955 did causing the fatal error with >) but this should not be interpreted as formula but only as part of string. How can I solve the problem?
The PHPExcel calculation engine is called by default when you save, but you can tell the writer not to apply it by calling
$objWriter->setPreCalculateFormulas(false);
before the call to save
When you set a cell value with a call to setCellValue() or similar, PHPExcel will attempt to identify the datatype and set it appropriately internally (in exactly the same way as MS Excel) using the value binder. Cells that contain a = as the first character will be considered as formulae by this.
If you want to ensure that they are treated as strings instead of formulae, then the easiest approach is to use setCellValueExplicit() instead.

How to insert huge formulas in PhpExcel?

Need your help with problem:
I need to Insert Formulas in the cells.
Simple Formulas like =A1+A2 are uploading OK.
But such as "=(C18100%/D18)100%" don't upload. Just empty cells.
Also as i'm from Ukraine, i need to upload formulas in my own language. Example:
=(((((C17(1-(Скидка+НакопСкидка))(1-Самовывоз)))(1-ПоФакту)))(1-Скидка_Упаковка))
Attemp to upload such formula gives an error:
Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with message 'Лист3!G17 -> Formula Error: Expecting ')'' in /var/www/zoobonus/zoobonus.ua/php_classes_2.1/Classes/PHPExcel/Cell.php:300 Stack trace: #0 /var/www/zoobonus/zoobonus.ua/php_classes_2.1/Classes/PHPExcel/Writer/Excel5/Worksheet.php(460): PHPExcel_Cell->getCalculatedValue() #1 /var/www/zoobonus/zoobonus.ua/php_classes_2.1/Classes/PHPExcel/Writer/Excel5.php(187): PHPExcel_Writer_Excel5_Worksheet->close() #2 /var/www/zoobonus/zoobonus.ua/templates/account/price_list/blank_for_all.php(75): PHPExcel_Writer_Excel5->save('/var/www/zoobon...') #3 /var/www/zoobonus/zoobonus.ua/admin/outlet_report.php(45): include('/var/www/zoobon...') #4 {main} thrown in /var/www/zoobonus/zoobonus.ua/php_classes_2.1/Classes/PHPExcel/Cell.php on line 300
How to fix this problems?
=(C18100%/D18)100%
is not a valid excel formula (missing operator between (C18100%/D18) and 100%
=(((((C17(1-(Скидка+НакопСкидка))(1-Самовывоз)))(1-ПоФакту)))(1-Скидка_Упаковка))
Are those named ranges (e.g. Скидка) that you're using in that formula?
I don't believe that C17 is a function in MS Excel, but it looks as though you are using it as one here.
Another problem lies in the lack of operator between -(Скидка+НакопСкидка)) and (1-Самовывоз))) and between (1-Самовывоз))) and (1-ПоФакту))) and between (1-ПоФакту))) and (1-Скидка_Упаковка))
I never realised that MS Excel allowed you to link operands without any operator, and can't find any version of MS Excel that will actually allow me to enter such a formula without complaining about it, so again I'd suggest that it is an invalid formula.
=(C18*100%/D18)*100% - i have repair the formula. It still doesn't want to insert in the cell. Why?
=(((((C17(1-(Скидка+НакопСкидка))(1-Самовывоз)))(1-ПоФакту)))(1-Скидка_Упаковка)) - thanks, it was really invalid formula, words like "Скидка" are links on cells. So i repeaired it on =(1-D7)*17 and it inserts now.

Formula error in PHPExcel

i have a strange issue with phpexcel on a pair of formulas and can't figure the source of the problem. (Other simple math formulas work, only this fails).
Since the php report is quite long i'll get straight to the point.
Setting this formula like this
$objPHPExcel->getActiveSheet()->setCellValue("D$cuenta_empleados", "=$'asientos_title'.K$cuadro_row" );
Throws me this
Fatal error: Uncaught exception 'Exception' with message 'INPUT NOMINA Agosto!D8 -> Formula Error: An unexpected error occured' in /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/php/inc/PHPExcel/Cell.php:293 Stack trace:
#0 /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/php/inc/PHPExcel/Writer/Excel5/Worksheet.php(455): PHPExcel_Cell->getCalculatedValue()
#1 /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/php/inc/PHPExcel/Writer/Excel5.php(194): PHPExcel_Writer_Excel5_Worksheet->close()
#2 /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/php/classes/Everything.class.php(2361): PHPExcel_Writer_Excel5->save('../../reports/1...')
#3 /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/php/classes/Everything.class.php(3813): Everything->create_act_entry(Array, Array, Array, Array, Array)
#4 /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/controllers/common/generar.php(68): Everything->gen_docs(Array, Array, Array)
#5 {main} thrown in /Users/PolCPP/Documents/Proyectos/Activos/beneficiat/php/inc/PHPExcel/Cell.php on line 293
So to debug it i remove the = to avoid it's calculation. I check it on openoffice. And i see
'ASIENTOS Agosto'.K4
And adding the = in front of it works.
The second formula i have issues it's a condition one (same issue, it can generate it but it works on php)
=IF(D22>O22;D22-O22;0)
The developer documentation states that you need to us US/UK separators in formulae.
Quoting:
4.6.4. Write a formula into a cell
Inside the Excel file, formulas are always stored as they would appear in an English version of Microsoft
Office Excel, and PHPExcel handles all formulae internally in this
format. This means that the following rules hold:
• Decimal separator
is '.' (period)
• Function argument separator is ',' (comma)
• Matrix
row separator is ';' (semicolon)
• English function names must be used
This is regardless of which language version of Microsoft Office Excel
may have been used to create the Excel file.
so
=IF(D22>O22,D22-O22,0)
rather than
=IF(D22>O22;D22-O22;0)
The only exception that applies is if you have set locale settings for formulae as described in section 4.6.5 of that document
The separator for a worksheet in a cell reference is the exclamation mark:
'ASIENTOS Agosto'!K4
not
'ASIENTOS Agosto'.K4
Formula pre-calculation
By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large
spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->setPreCalculateFormulas(false); isso resolver
$objWriter->save("05featuredemo.csv");
Im using this PHPExcel class for database import purposes and i got the same error.
Some debugging showed, that this content of a table cell caused the error:
=- die Beschaffungsplattform für Geschäftskunden
I figured out, that the exception is thrown on purpose at:
PHPExcel/Classes/PHPExcel/Cell.php on line 288 (current PHPExcel Version v1.7.6)
throw(new Exception($this->getParent()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage()));
So i just deleted this exception and returning an empty string instead:
$result = "";
Its a bad Workaround but works like a charme :)

Categories