PHPexcel formula IFERROR - php

I'm using PHP excel 1.8.0. I have searched everywhere but I don't understand why following error occures and my excel file is corrupted.
Uncaught exception 'PHPExcel_Calculation_Exception' with message 'Worksheet!K2 -> Formula Error: An unexpected error occured'
I have to use ISO 8859-2 encoding
$formula = iconv('ISO-8859-2', 'UTF-8//IGNORE//TRANSLIT', '=IFERROR(IF(OR(C'.$row.'="string1";C'.$row.'="strin2");D'.$row.';" ");" ")');
$objPHPExcel->getActiveSheet()->setCellValue($where, $formula);
I tried setting formula without =. After that when I open my excel file all formulas are set properly without = mark. Then if I add it manually to the formula, it works. But with code like you can see it, formulas are broken.
I have Also tried adding = after I used iconv, but nothing has changed file was still broken. I would be glad if someone could help me with this problem.

From the PHPExcel documentation:
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.
You're using a semi-colon (;) as a function argument separator

If you get problem in working of IFERROR while export then you can use
$sheet->setCellValue($cell_name, "=IF(ISERROR($val1*$val2),0,$val1*$val2)");
It works for me :)

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, why don't my line breaks appear if using PHPExcel_RichText?

I'm trying to use PHPExcel to produce something which looks like this:
Label:
This is the value
Where "Label" is dark red, and "This is the value" is on a new line, in the same cell.
I've been using the following code:
$text = new PHPExcel_RichText();
$label = $text->createTextRun("This is the label: ");
$label->getFont()->setBold(true);
$label->getFont()->setItalic(true);
$label->getFont()->setColor(new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_DARKRED));
$text->createText(PHP_EOL . "This is the value");
$workbook->getActiveSheet()->getCell('A1')->setValue($text);
$workbook->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
But for some reason this doesn't seem to be working. I've tried "\r" and "\n" in place of PHP_EOL (being careful to use double quotes instead of single ones).
I've also tried moving the PHP_EOL to the label text.
If I call setValue($text . PHP_EOL) I lose the formatting, but the line break works.
I'm on a Mac using Excel 2016 if that makes any difference. Unfortunately I'm not able to test on a different version of Excel. Can someone show me how to fix this?
I have just tried your code on my Mac and it works fine but I have already patched several files of the phpExcel package.
I have unzipped the Excel file generated with phpExcel and compared the xml files with those from a regular Excel file and found some differences.
One of them is how bold is specified in the sharedStrings.xml file.
in a phpExcel generated file you have:
<b val="1"/>
and in a regular Excel file
<b/>
So in StringTable.php, in writeRichText, I have changed
// Bold 1
if($element->getFont()->getBold())
{
$objWriter->startElement($prefix.'b');
$objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
$objWriter->endElement();
}
to
// Bold 1
if($element->getFont()->getBold())
{
$objWriter->startElement($prefix.'b');
$objWriter->endElement();
}
and I did the same for the other true/false properties.
It was not enough to solve my own problem of newlines disappearing in RichTextObjects, but i have given the other patches I've done in PHPExcel toRichTextObject only showing newlines after saving file again manually.
So that, when I use your code, the newlines are correctly set and visible.
Hope it will solve your problem!
Using Excel for Mac 2011 on latest OS X. Tried to add PHP_EOL and/or "\n".
$cellValue->createText(PHP_EOL);
$cellValue->createText("\n");
Neither is creating a new line when using PHPExcel_RichText.

PHP league/csv Reader How to know which delimiter was used?

When using league/csv to read a csv file, how could I know which csv controls have been used to parse the file ?
I made different csv files :
delimiter_colon.csv {exported from excel with colon delimiter}
delimiter_tab.csv {exported from excel with tab delimiter}
delimiter_semicolon.csv {exported from excel with semicolon delimiter}
etc...
When using
use League\Csv\Reader;
...
//Read csv from path
$csvReader = Reader::createFromPath( $CSVFile->path );
//get the current delimiter ? Nope always the default one ...
$this->delimiter = $csvReader->getDelimiter();
EDIT: What I want to know is which delimiter has been used by the current reader.
Not the delimiter in the csv file itself.
Whatever the file I use to read the csv, it always gives "," {coma}
So I'm asking here:
How to know which delimiter/enclosure were used to parse the current csv Reader ?
I've also tried using getIterator(). Get default values too.
If you are using the latest version of the library you can simply use Reader::fetchDelimitersOccurrence as explained in the documentation. But be aware that the method will only return information about the suggested delimiters you supply. Because it is not possible for the method to know which delimiter is in use. The result is only a hint that needs to be confirm by the CSV provider.

Formula disappear php excel

I'm trying to use a formula which is not implanted in PHPExcel but in excel, COUNTIFS whit 2 arguments.
I update the formula file in phpexcel and I add
$objWriter->setPreCalculateFormulas(false);
To have no generation errors.
But when I open the file with excel I only have a 0 and no formula. I also have an open and repair and this remove the function I think
This is for example
$sheet->setCellValue($this->intToChar($j).($end+$i),'=COUNTIFS(E$17:F$47;$B58;E$16:F$46;$B58)');
If I just add
$sheet->setCellValue($this->intToChar($j).($end+$i),'COUNTIFS(E$17:F$47;$B58;E$16:F$46;$B58)');
and I set an = in excel it works
Thanks for your help
The documentation explicitly states that commas (,) should be used as an argument separator for function arguments, unless you've explicitly set a locale for the calculation engine; so you need
$sheet->setCellValue(
$this->intToChar($j).($end+$i),
'=COUNTIFS(E$17:F$47,$B58,E$16:F$46,$B58)'
);
And why are you using a homebrew intToChar() function when there's a built-in PHPExcel_Cell::stringFromColumnIndex() function?

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