Formula error an unexpected error occurred phpspreadsheet

This is: - [X ] a bug report - [ ] a feature request - [ ] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsh...

This is:

- [X ] a bug report
- [ ] a feature request
- [ ] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet)

What is the expected behavior?

calculate the formula as in Excel:

Open a xlsm
Add data to some cells
Calculate a cell value

What is the current behavior?

A simple setCellValue and getCalculatedValue script return the following error:

Fatal error: Uncaught PhpOfficePhpSpreadsheetCalculationException: Inputs!E22 -> Gross!C22 -> Gross!C77 -> Gross!C79 -> Gross!C37 -> Gross!C39 -> Gross!C40 -> Cost!M25 -> Cost!L25 -> Cost!F25 -> Selected Sum!B18 -> Formula Error: An unexpected error occured in /var/www/vhosts/testxmlx.local/html/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php:274 
Stack trace: 
#0 /var/www/vhosts/testxmlx.local/html/test/exp/rate/fp.php(22): PhpOfficePhpSpreadsheetCellCell->getCalculatedValue() 
#1 {main} thrown in /var/www/vhosts/testxmlx.local/html/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php on line 274

As in the error message the Cells directly involved in the calculation are:

Inputs!E22 -> 	=IF(bMoreInputsRequired,"",ROUNDUP('Gross'!C22,2))

Gross!C22 ->	=C77
Gross!C77 ->	=IFERROR(C79+C81+C86+C92+C94,"No Scale Presented")
Gross!C79 ->	=C37*(1+PA_IPT)
Gross!C37 ->	=C17-SUM(C39,C44,C50,C52)
Gross!C39 ->	=SUM(C40:C42)
Gross!C40 ->	=('Cost'!$M$25*0.95/(1-In_Tolerance))/C15

Cost!M25 -> 	=IFERROR(B25*C25*L25*($M$5="No")+($M$5="Yes")*($M$54*TLR-(1+Financial_IPT)*$M$40-(1+Assistance_IPT)*$M$34)/(1+PA_IPT),0)
Cost!L25 -> 	=IFERROR(IF(F25<C25,F25/(C25*INDEX($AC$51:$AG$75,MATCH(A25,$AB$51:$AB$75,0),3)),((INDEX($AC$51:$AG$75,MATCH(A25,$AB$51:$AB$75,0),5)-1)/(INDEX($AC$51:$AG$75,MATCH(A25,$AB$51:$AB$75,0),1)-C25*INDEX($AC$51:$AG$75,MATCH(A25,$AB$51:$AB$75,0),3)))*(MIN(F25,$AC$79)-C25*INDEX($AC$51:$AG$75,MATCH(A25,$AB$51:$AB$75,0),3))+1)*IF(K25="No",1,1-IFERROR(INDEX(Assumptions!$E197:$AO197,MATCH(Product_Combination,Assumptions!$E$186:$AO$186,0)),0))*($M$5="No")+($M$5="Yes"),"-")
Cost!F25 -> 	=INDEX('Selected Sum'!$B18:$J18,MATCH("Yes",'Selected Sum'!$B$3:$J$3,0))

Selected Sum!B18 ->	=SUMIFS(Inputs!$X:$X,Inputs!$T:$T,$A18)

What are the steps to reproduce?

Unfortunately I can’t provide the xlsm, so you can’t really reproduce the error.
Anyway this is our test code:

<?php
require(dirname(__FILE__) . "/../../../vendor/autoload.php");

$reader = new PhpOfficePhpSpreadsheetReaderXlsx();
$spreadsheet = $reader->load(dirname(__FILE__) . "/data/test.xlsm");

$sheetData = $spreadsheet->getActiveSheet();

$spreadsheet->getActiveSheet()->setCellValue('B4','test');
$spreadsheet->getActiveSheet()->setCellValue('B5','12345');
$spreadsheet->getActiveSheet()->setCellValue('B9','1');
$spreadsheet->getActiveSheet()->setCellValue('B10','Public');
$spreadsheet->getActiveSheet()->setCellValue('B19','3');

$spreadsheet->getActiveSheet()->setCellValue('E4','XYZ_2018');
$spreadsheet->getActiveSheet()->setCellValue('E9','20');
$spreadsheet->getActiveSheet()->setCellValue('E10','10');
$spreadsheet->getActiveSheet()->setCellValue('E11','5');
$spreadsheet->getActiveSheet()->setCellValue('E13','10%');

echo $spreadsheet->getActiveSheet()->getCell('E22')->getCalculatedValue();
?>

We also have a similar error with just a reader / writer script

<?php
require(dirname(__FILE__) . "/../../../vendor/autoload.php");

$reader = new PhpOfficePhpSpreadsheetReaderXlsx();
$spreadsheet = $reader->load(dirname(__FILE__) . "/data/test.xlsm");


$writer = new PhpOfficePhpSpreadsheetWriterXlsx($spreadsheet);
$writer->save(dirname(__FILE__) . "/data/save.xlsx");

?>

Which versions of PhpSpreadsheet and PHP are affected?

PhpSpreadsheet : 1.5.0 & dvelop
PHP: 7.2

Maybe it’s relate to close issues #182

Содержание

  1. Uncaught PhpOfficePhpSpreadsheetCalculationException: Riepilogo!B2 -> Riepilogo!B4 -> Formula Error: An unexpected error occured #182
  2. Comments
  3. What is the expected behavior?
  4. What is the current behavior?
  5. What are the steps to reproduce?
  6. Which versions of PhpSpreadsheet and PHP are affected?
  7. Ошибка формулы в PHPExcel
  8. Ошибка формулы в PHPExcel
  9. 3 ответы
  10. Ошибка формулы в PHPExcel
  11. 3 ответа
  12. Формула PHPExcel ЕСЛИОШИБКА
  13. Ответы (2)

Uncaught PhpOfficePhpSpreadsheetCalculationException: Riepilogo!B2 -> Riepilogo!B4 -> Formula Error: An unexpected error occured #182

What is the expected behavior?

I load an xlsx template
I put some test data in cells
Write the new file

What is the current behavior?

When reading, get: Uncaught PhpOfficePhpSpreadsheetCalculationException: Riepilogo!B2 -> Riepilogo!B4 -> Formula Error: An unexpected error occured

What are the steps to reproduce?

Please provide a Minimal, Complete, and Verifiable example of code that exhibits the issue without relying on an external Excel file or a web server:

To reproduce this bug, first you need to solve the ISSUE #181 as I suggested.

The excel formula is: =SE(SOMMA(B4:B80)=’Liste presenze’!K8;» «;»ERRORE») in english =IF(SUM(B4:B80)=’Liste presenze’!K8;» «;»ERRORE»)
To test you need an external excel file, that i attach

Which versions of PhpSpreadsheet and PHP are affected?

The text was updated successfully, but these errors were encountered:

Hi there, I think i have the same issue.
when i use a formula with a reference to another sheet, it fails.

after i change the formula to a reference on the same sheet, it will pass. I think you are using different sheets also?

Yes, in the template there are 2 sheets.

I solved, deleting the second sheet 🙂 and copying and pasting the first sheet, the one dinamically generated 🙂

I know, it’s not a solution, but it works 🙂

@JosHonig if you are able to pinpoint exactly what goes wrong and find a fix, that would be very appreciated. Maybe the first step for that would be to reproduce the issue without external file, by creating a spreadsheet by code only.

the line below gives an error
=vlookup(A1,Sheet1!A:B,2,false)

and this one is working
=vlookup(A1,Sheet1!A1:B99999,2,false)

so refering to columns on another sheet is not working for me. (both creating from scratch and creating new)

Any update on this? Having the same problem with vlookup.

Nothing new from me unfortunately. I’m afraid my last comment still stands and one of you will have to debug it further to find a fix

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
If this is still an issue for you, please try to help by debugging it further and sharing your results.
Thank you for your contributions.

same issue here, when we are refering to another sheet in a formula =COUNTIF(Data!K:K;»>=30″),
we get the issue reported :/

I also still got this error when refering to another sheet in the same file

Still Same here :

works:
$sheet->setCellValue(‘D15’, «=SUM(‘name sheet!AL1:AL99999)»);

error :
$sheet->setCellValue(‘D15’, «=SUM(‘name sheet!AL:AL)»);

Column and Row Ranges have never been supported in formulae by the PHPSpreadsheet Calculation Engine; I’m currently working on them in the new replacement engine, but this is a complete and total rewrite, and takes time

Any updates on this? 🙂

Most of the examples here are using column or row ranges, which are not cleanly supported by PHPSpreadsheet’s calculation engine; references to other sheets in formulae should work, unsupported column or row ranges do not, whether in the same sheet or another sheet

Unfortunately this is still a living issue. Reference to other sheet in the same file crashes. It is not out of column or row ranges. Any workaround this?

The error seems to be when saving the file, the PHPSpreadsheet tries to read the formulae. I saw that on PHPExcel, lots of people had this problem but were able to solve it calling the method $objWriter->setPreCalculateFormulas(false);

Is there anything like this for PhpSpreadsheet? Couldn’t find in the docs.

ok, found the issue, this happens when the formula in some cell is invalid, that would in normal excel case give an error or in some case excel auto-corrects it so you cant re-produce the issue in excel in some case. in my case, some cells contained values like
=CONCATENATE(«+», «2.»)
which evaluates to +2. and there cant be a decimal at the end of the value in the cell

So debug your data

so, why is it on the OLD PHPExcel I was able to read the formula: =VLOOKUP(A3,’Current Inventory’!A:B,2,FALSE)
but on PhpOffice (which is supposed to be better), I get an exception and have to change my formula to look like:
=VLOOKUP(A3,’Current Inventory’!A1:B9999,2,FALSE).. this becomes a real pain for an existing spreadsheet with 5 worksheets and at least 5000 lines on each sheet..

isn’t there a simple way to edit the code to say something like..

I had a similar error message showing «Uncaught PhpOfficePhpSpreadsheetCalculationException:».
The field that was in question was having issue saving into Excel cell, and after testing, I found not all values fetched cause error.
The values were fetched from database using while loop. Excel must have had pre-determined the type of the cell after fetching multiple values, then decided to throw error on a value that it thinks it doesn’t match the type. I think this was the cause because after I setCellValueExplicit to TYPE_STRING for that cell, the error had disappeared.

excel by default (an option) stores all the data from the cells as you see it. if you turn of evaluation engine off on open, you still get your data in cells on open as you left it. so is there a way to turn of evaluation and just load the data?
i tried $reader->setReadDataOnly(true);
did not notice any effect on the evaluation just on the formatting, the sheet with vlookup formulas not loading.

Источник

Ошибка формулы в PHPExcel

У меня есть странная проблема с phpexcel по паре формул и не может определить источник проблемы. (Другие простые математические формулы работают, только это не удается).

Поскольку отчет php довольно длинный, я сразу доберусь до точки.

Устанавливая эту формулу следующим образом:

Итак, чтобы отладить его, я удаляю =, чтобы избежать его вычисления. Я проверяю его на openoffice. И я вижу

И добавление = перед ним работает.

Вторая формула я имеет проблемы с одним условием (одна и та же проблема, она может генерировать, но работает на php)

В документации разработчика указано, что вам нужны сепараторы US/UK в формулах.

Внутри файла Excel формулы всегда сохраняются, как они появятся в английской версии Microsoft Office Excel и PHPExcel обрабатывают все формулы внутри формат. Это означает, что соблюдаются следующие правила:

• Десятичный разделитель является ‘.’ (период)

• Разделитель аргументов функции: “,” (запятая)

• Матрица разделитель строк – ‘;’ (точка с запятой)

• Должны использоваться английские имена функций

Это независимо от того, какая языковая версия Microsoft Office Excel могут быть использованы для создания файла Excel.

Единственное исключение, которое применяется, – это если вы установили языковые настройки для формул, как описано в разделе 4.6.5 этого документа.

Сепаратором для листа в ссылке на ячейку является восклицательный знак:

Предварительный расчет формул
По умолчанию этот сценарий предварительно вычисляет все формулы в электронной таблице. Это может быть медленным на больших
электронных таблицах и, возможно, даже нежелательных. Однако вы можете отключить предварительный расчет формулы:

$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->setPreCalculateFormulas(false); isso resolver
$objWriter->save(«05featuredemo.csv»);

Im, используя этот класс PHPExcel для целей импорта базы данных, и я получил ту же ошибку.
Некоторая отладка показала, что это содержимое ячейки таблицы вызвало ошибку:

Я понял, что исключение выбрано специально:

PHPExcel/Classes/PHPExcel/Cell.php в строке 288 (текущая версия PHPExcel v1.7.6)

Итак, я просто исключил это исключение и вместо этого вернул пустую строку:

Плохо обходное решение, но работает как charme:)

Источник

Ошибка формулы в PHPExcel

У меня странная проблема с phpexcel в паре формул, и я не могу понять источник проблемы. (Другие простые математические формулы работают, только это не работает).

Поскольку отчет по php довольно длинный, я сразу перейду к делу.

Установка этой формулы следующим образом

Бросает мне это

Поэтому, чтобы отладить его, я удаляю =, чтобы избежать его расчета. Проверяю в опеноффисе. и я вижу

И добавление = перед ним работает.

Вторая формула, у меня есть проблемы, это первое условие (такая же проблема, она может ее генерировать, но работает на php)

задан 25 июн ’12, 13:06

3 ответы

В документации разработчика указано, что вам нужно использовать разделители США/Великобритании в формулах.

Внутри файла Excel формулы всегда хранятся в том виде, в каком они будут отображаться в английской версии Microsoft Office Excel, и PHPExcel обрабатывает все формулы внутри этого формата. Это означает, что выполняются следующие правила:

• Десятичный разделитель — «.». (период)

• Разделителем аргументов функции является ‘,’ (запятая).

• Разделителем строк матрицы является ‘;’ (точка с запятой)

• Должны использоваться имена функций на английском языке.

Это не зависит от того, какая языковая версия Microsoft Office Excel могла использоваться для создания файла Excel.

Единственное исключение, которое применяется, если вы установили языковые настройки для формул, как описано в разделе 4.6.5 этого документа.

Разделителем рабочего листа в ссылке на ячейку является восклицательный знак:

Источник

Ошибка формулы в PHPExcel

У меня есть странная проблема с phpexcel по паре формул и не может определить источник проблемы. (Другие простые математические формулы работают, только это не удается).

Поскольку отчет php довольно длинный, я сразу доберусь до точки.

Устанавливая эту формулу следующим образом:

Итак, чтобы отладить его, я удаляю =, чтобы избежать его вычисления. Я проверяю его на openoffice. И я вижу

И добавление = перед ним работает.

Вторая формула я имеет проблемы с одним условием (одна и та же проблема, она может генерировать, но работает на php)

3 ответа

В документации разработчика указано, что вам нужны сепараторы US/UK в формулах.

Внутри файла Excel формулы всегда сохраняются, как они появятся в английской версии Microsoft Office Excel и PHPExcel обрабатывают все формулы внутри формат. Это означает, что соблюдаются следующие правила:

• Десятичный разделитель является ‘.’ (период)

• Разделитель аргументов функции: «,» (запятая)

• Матрица разделитель строк — ‘;’ (точка с запятой)

• Должны использоваться английские имена функций

Это независимо от того, какая языковая версия Microsoft Office Excel могут быть использованы для создания файла Excel.

Единственное исключение, которое применяется, — это если вы установили языковые настройки для формул, как описано в разделе 4.6.5 этого документа.

Сепаратором для листа в ссылке на ячейку является восклицательный знак:

Источник

Формула PHPExcel ЕСЛИОШИБКА

Я использую PHP excel 1.8.0. Я искал везде, но я не понимаю, почему возникает следующая ошибка, и мой файл excel поврежден.

Я должен использовать кодировку ISO 8859-2

Я попытался установить формулу без = . После этого, когда я открываю свой файл Excel, все формулы устанавливаются правильно без отметки = . Затем, если я добавлю его вручную в формулу, он сработает. Но с таким кодом, как вы его видите, формулы не работают. Я также пытался добавить = после того, как использовал iconv, но ничего не изменилось, файл все еще был сломан. Буду рад, если кто-то поможет мне с этой проблемой.

Ответы (2)

Введите формулу в ячейку

Внутри файла Excel формулы всегда хранятся в том виде, в каком они будут отображаться в английской версии Microsoft Office Excel, и PHPExcel обрабатывает все формулы внутри этого формата. Это означает, что выполняются следующие правила:

  • Десятичный разделитель ‘.’ (период)
  • Разделитель аргументов функции — ‘,’ (запятая)
  • Разделитель строк матрицы ‘;’ (точка с запятой)
  • Должны использоваться английские названия функций.

Это не зависит от того, какая языковая версия Microsoft Office Excel могла использоваться для создания файла Excel.

Вы используете точку с запятой ( ; ) в качестве разделителя аргументов функции.

Если у вас возникли проблемы с работой IFERROR при экспорте, вы можете использовать

Источник

Thank you very much for your detailed analysis! :)

Indeed the debugging tool could find an error, I’ll post it here.

I have used the script:

<?php

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetCalculationCalculation;

error_reporting(E_ALL);
set_time_limit(0);

date_default_timezone_set('UTC');

// Adjust the path as required to reference the PHPSpreadsheet Bootstrap file
// require_once __DIR__ . '/../src/Bootstrap.php';
require 'vendor/autoload.php';
require '_config.php';

$reader = new PhpOfficePhpSpreadsheetReaderXlsx();
$spreadsheet = $reader->load( $excelFilePath );

$worksheet = $spreadsheet->getSheetByName( 'Konten' );
// Initialise the calculation engine for debug logging
$spreadSheet = new Spreadsheet();
$calculationEngine = Calculation::getInstance($spreadSheet);
$debugLog = $calculationEngine->getDebugLog();

$calculationEngine->flushInstance();
$debugLog->setWriteDebugLog(true);


// The cell address in the worksheet that contains the formula
$cell = 'AC5';

$formulaValue = $worksheet->getCell($cell)->getValue();
echo PHP_EOL, 'Formula value for evaluation is ', $formulaValue, PHP_EOL;

$canExecuteCalculation = false;
try {
    $tokens = $calculationEngine->parseFormula($formulaValue, $worksheet->getCell($cell));
    echo 'Parser Stack :-', PHP_EOL;
    print_r($tokens);
    $canExecuteCalculation = true;
} catch (Exception $e) {
    echo "PARSER ERROR: ", $e->getMessage(), PHP_EOL;

    echo 'Parser Stack :-';
    print_r($tokens);
}

if ($canExecuteCalculation) {
    //  calculate
    try {
        $cellValue = $worksheet->getCell($cell)->getCalculatedValue();

		echo PHP_EOL, 'Result is ', $cellValue, PHP_EOL;

        echo 'Evaluation Log:', PHP_EOL;
        print_r($debugLog->getLog());
    } catch (Exception $e) {
        echo "CALCULATION ENGINE ERROR: ", $e->getMessage(), PHP_EOL;

        echo 'Evaluation Log:', PHP_EOL;
        print_r($debugLog->getLog());
    }
}

I have used AB5 instead of AB16 — all the ABs look similar. Please don’t be confused.

Formula value for evaluation is =AC5+AD5
Parser Stack :-
Array
(
    [0] => Array
        (
            [type] => Cell Reference
            [value] => AC5
            [reference] => AC5
        )

    [1] => Array
        (
            [type] => Cell Reference
            [value] => AD5
            [reference] => AD5
        )

    [2] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

)
CALCULATION ENGINE ERROR: Konten!AB5 -> Konten!AC5 -> Übersicht!S389 -> Formula Error: An unexpected error occurred
Evaluation Log:
Array
(
)

The calculated fomula seems legit to me, but to my mind, an operator is missing between array element 0 and 1?

Debug for AC5:

Formula value for evaluation is =F52+F53+F54+F112+F139+Übersicht!S389+F181+Übersicht!S577+F204+F267
Parser Stack :-
Array
(
    [0] => Array
        (
            [type] => Cell Reference
            [value] => F52
            [reference] => F52
        )

    [1] => Array
        (
            [type] => Cell Reference
            [value] => F53
            [reference] => F53
        )

    [2] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [3] => Array
        (
            [type] => Cell Reference
            [value] => F54
            [reference] => F54
        )

    [4] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [5] => Array
        (
            [type] => Cell Reference
            [value] => F112
            [reference] => F112
        )

    [6] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [7] => Array
        (
            [type] => Cell Reference
            [value] => F139
            [reference] => F139
        )

    [8] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [9] => Array
        (
            [type] => Cell Reference
            [value] => Übersicht!S389
            [reference] => Übersicht!S389
        )

    [10] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [11] => Array
        (
            [type] => Cell Reference
            [value] => F181
            [reference] => F181
        )

    [12] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [13] => Array
        (
            [type] => Cell Reference
            [value] => Übersicht!S577
            [reference] => Übersicht!S577
        )

    [14] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [15] => Array
        (
            [type] => Cell Reference
            [value] => F204
            [reference] => F204
        )

    [16] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

    [17] => Array
        (
            [type] => Cell Reference
            [value] => F267
            [reference] => F267
        )

    [18] => Array
        (
            [type] => Binary Operator
            [value] => +
            [reference] => 
        )

)
CALCULATION ENGINE ERROR: Konten!AC5 -> Übersicht!S389 -> Formula Error: An unexpected error occurred
Evaluation Log:
Array
(
)

Debug for Übersicht!S389:

Formula value for evaluation is =IF(Wettdaten[[#This Row],[Status]]="","",
IF(OR(Wettdaten[[#This Row],[Status]]="Offen",Wettdaten[[#This Row],[Status]]="ToDo"),0,
Wettdaten[[#This Row],[Zurück]]-Wettdaten[[#This Row],[Einsatz]]))
PARSER ERROR: Formula Error: An unexpected error occurred
Parser Stack :-PHP Notice:  Undefined variable: tokens in /.../debug.php on line 45

Indeed there is a formular here 🤔
Excel is calculating it correctly, I can see the value in the file. Is this an error with the formula or with PHPSpreadsheet?

Is this enough information?

This is:

- [x] a bug report
- [ ] a feature request
- [x] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet)

What is the expected behavior?

Calculation should complete normally.

What is the current behavior?

Fatal error: Uncaught PhpOfficePhpSpreadsheetCalculationException: Worksheet!
D1 -> Formula Error: An unexpected error occurred in C:gitPhpSpreadsheetsrcPhpSpreadsheetCellCell.php on line 274

I undid some try catches and added an echo after the assignment to isOperandOrFunction in Calculation around line 3866 to capture more information, so the line numbers after that may be off by a couple of lines. text is substr($formula, $index):
text=SUMIF(A1:A2,B1,C1:C2)
text=A1:A2,B1,C1:C2)
text=:A2,B1,C1:C2)
text=A2,B1,C1:C2)
text=,B1,C1:C2)
text=B1,C1:C2)
text=,C1:C2)
text=C1:C2)
text=:C2)
text=C2)
text=)
text=»»»TEXT WITH QUOTES»»»=»»TEXT WITH QUOTES»»
text==»»TEXT WITH QUOTES»»
text=»»TEXT WITH QUOTES»»
text=TEXT WITH QUOTES»»
text=EXT WITH QUOTES»»
text=WITH QUOTES»»
text=QUOTES»»
text=»»
text=»

Fatal error: Uncaught PhpOfficePhpSpreadsheetCalculationException: Formula Error: An unexpected error occurred in C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php on line 5086

Call Stack:
0.0003 403360 1. {main}() C:gitxsumifbug.php:0
0.0327 988336 2. xcondfmt::testSumif() C:gitxsumifbug.php:20
0.0668 4123144 3. PhpOfficePhpSpreadsheetCellCell->getCalculatedValue() C:gitxsumifbug.php:16
0.0668 4123144 4. PhpOfficePhpSpreadsheetCalculationCalculation->calculateCellValue() C:gitPhpSpreadsheetsrcPhpSpreadsheetCellCell.php:258
0.0668 4123896 5. PhpOfficePhpSpreadsheetCalculationCalculation->_calculateFormulaValue() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:3237
0.0700 4140248 6. PhpOfficePhpSpreadsheetCalculationCalculation->processTokenStack() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:3444
0.0717 4217728 7. call_user_func_array:{C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:4714}() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:4714
0.0724 4251616 8. PhpOfficePhpSpreadsheetCalculationStatisticalConditional::SUMIF() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:4714
0.0736 4351984 9. PhpOfficePhpSpreadsheetCalculationDatabaseDSum::evaluate() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationStatisticalConditional.php:188
0.0742 4356552 10. PhpOfficePhpSpreadsheetCalculationDatabaseDatabaseAbstract::getFilteredColumn() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationDatabaseDSum.php:42
0.0742 4356552 11. PhpOfficePhpSpreadsheetCalculationDatabaseDatabaseAbstract::filter() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationDatabaseDatabaseAbstract.php:77
0.0757 4411840 12. PhpOfficePhpSpreadsheetCalculationDatabaseDatabaseAbstract::executeQuery() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationDatabaseDatabaseAbstract.php:71
0.0758 4412488 13. PhpOfficePhpSpreadsheetCalculationCalculation->_calculateFormulaValue() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationDatabaseDatabaseAbstract.php:145
0.0758 4412896 14. PhpOfficePhpSpreadsheetCalculationCalculation->internalParseFormula() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:3444
0.0786 4418552 15. PhpOfficePhpSpreadsheetCalculationCalculation->raiseFormulaError() C:gitPhpSpreadsheetsrcPhpSpreadsheetCalculationCalculation.php:4180

/php.ln: Exit 255.

What are the steps to reproduce?

Please provide a Minimal, Complete, and Verifiable example of code that exhibits the issue without relying on an external Excel file or a web server:

<?php

require __DIR__ . '/vendor/autoload.php';

// Create new Spreadsheet object
        $spreadsheet = new PhpOfficePhpSpreadsheetSpreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $matchText = '"text with quotes"';
        $sheet->getCell('A1')->setValue($matchText);
        $sheet->getCell('A2')->setValue(2);
        $sheet->getCell('B1')->setValue($matchText);
        $sheet->getCell('C1')->setValue(10);
        $sheet->getCell('C2')->setValue(100);
        $sheet->getCell('D1')->setValue('=SUMIF(A1:A2,B1,C1:C2)');
        print_r($sheet->getCell('D1')->getCalculatedValue());

It seems that Calculation is having trouble with the trailing double quote, but I’m not sure how to fix it. If I change matchText so that it doesn’t contain the double quotes, everything works.

Which versions of PhpSpreadsheet and PHP are affected?

All PHP. Current, and probably for some time back, versions of PhpSpreadsheet.

  1. Home

  2. php — PhpSpreadsheet fatal errro when i tried add graphic

795 votes

1 answers

Get the solution ↓↓↓

Fatal error: Uncaught PhpOfficePhpSpreadsheetCalculationException:
Formula Error: An unexpected error occurred in
C:xampphtdocsgraficas_excelvendorphpofficephpspreadsheetsrcPhpSpreadsheetCalculationCalculation.php:5224
Stack trace:
#0
C:xampphtdocsgraficas_excelvendorphpofficephpspreadsheetsrcPhpSpreadsheetCalculationCalculation.php(4305):
PhpOfficePhpSpreadsheetCalculationCalculation->raiseFormulaError(‘Formula
Error: …’)
#1
C:xampphtdocsgraficas_excelvendorphpofficephpspreadsheetsrcPhpSpreadsheetCalculationCalculation.php(3539):
PhpOfficePhpSpreadsheetCalculationCalculation->internalParseFormula(‘!
Worksheet $ B…’, Object(PhpOfficePhpSpreadsheetCellCell))
#2
C:xampphtdocsgraficas_excelvendorphpofficephpspreadsheetsrcPhpSpreadsheetChartDataSeriesValues.php(363):
PhpOfficePhpSpreadsheetCalculationCalculation->_calculateFormulaValue(‘!
Worksheet $ B…’, NULL, Object(PhpOfficePhpSpreadsheetCellCell))

#3 C:xampphtdocsgraficas_excelvendorphpofficephpspreadsh in C:xampphtdocsgraficas_excelvendorphpofficephpspreadsheetsrcPhpSpreadsheetCalculationCalculation.php
on line 5224

Hi everybody.

I tried create chart in excel fo phpoffice/phpspreadsheet, but when i tried add graph the app is broken.

my code

<?php

require '../vendor/autoload.php';

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
use PhpOfficePhpSpreadsheetChartChart;
use PhpOfficePhpSpreadsheetChartDataSeries;
use PhpOfficePhpSpreadsheetChartDataSeriesValues;
use PhpOfficePhpSpreadsheetChartLayout;
use PhpOfficePhpSpreadsheetChartLegend;
use PhpOfficePhpSpreadsheetChartPlotArea;
use PhpOfficePhpSpreadsheetChartTitle;
use PhpOfficePhpSpreadsheetChartAxis;

$spreadsheet = new Spreadsheet();

$worksheet = $spreadsheet->getActiveSheet();

$worksheet->fromArray(
        [
            ['Shinjuku', 778, 618],
            ['Ikebukuro', 566, 516],
            [' Tokyo ', 452, 549],
            [' Shinagawa ', 378, 566],
            [' Shibuya ', 370, 669],
        ]
);
$xAxisTickValues = [
    New DataSeriesValues(DataSeriesValues :: DATASERIES_TYPE_STRING, '! Worksheet $ A $ 1: $ A $ 5', Null, 5), //Shinjuku-Shibuya
];

$dataSeriesValues = [
    New DataSeriesValues(DataSeriesValues :: DATASERIES_TYPE_NUMBER, '! Worksheet $ B $ 1: $ B $ 5', Null, 5), //each value of the number of passengers
];

$series = new DataSeries(
        DataSeries::TYPE_BARCHART, //plotType
        DataSeries::GROUPING_STANDARD, //plotGrouping
        range(0, count($dataSeriesValues) - 1), //plotOrder
        [], //plotLabel
        $xAxisTickValues, //plotCategory
        $dataSeriesValues//plotValues
);

$series->setPlotDirection(DataSeries::DIRECTION_COL);
$plotArea = new PlotArea(null, [$series]);
$title = new Title('number of passengers per day');

$yaxis = new Axis();
$xaxis = new Axis();
$yaxis->setAxisOptionsProperties('low', null, null, null, null, null, 0, 100, null, null);
$yaxis->setLineParameters('FFFFFF', 100, Axis::EXCEL_COLOR_TYPE_ARGB);
$xaxis->setAxisOptionsProperties('low', null, null, null, null, null, 0, 0, null, null);
$legend1 = new Legend(Legend::POSITION_RIGHT, null, false);
$yAxisLabel = new Title('');
$chart = new Chart(
        'bar chart', //name
        $title, //title
        $legend1, //legend
        $plotArea, //plotArea
        true, //plotVisibleOnly
        DataSeries::EMPTY_AS_GAP, // displayBlanksAs
        null, // xAxisLabel
        $yAxisLabel, // yAxisLabel
        $yaxis,
        $xaxis
);

$worksheet->addChart($chart);

$writer = new Xlsx($spreadsheet);

$writer->setIncludeCharts(true);

$writer->save('passengers.xlsx');

2021-11-29

Write your answer


55

votes

Answer

Solution:

I have change my code.

$worksheet->fromArray(
        [
            ['', 'number of passengers per day',''],
            ['Shinjuku', 7787.81, 618],
            ['Ikebukuro ', 566, 516],
            [' Tokyo ', 452, 549],
            [' Shinagawa ', 378, 566],
            [' Shibuya ', 370, 669],
        ]
);

$xAxisTickValues = [
    New DataSeriesValues(DataSeriesValues :: DATASERIES_TYPE_STRING, 'Worksheet!$A$2:$A$6', Null, 5), //Shinjuku-Shibuya
];

$dataSeriesValues = [
    New DataSeriesValues(DataSeriesValues :: DATASERIES_TYPE_NUMBER, 'Worksheet!$B$2:$B$6', Null, 5), //each value of the number of passengers
    New DataSeriesValues(DataSeriesValues :: DATASERIES_TYPE_NUMBER, 'Worksheet!$C$2:$C$6', Null, 5), //each value of the number of passengers
];

ItВґs work but when i open excel i need to recover form xml error?


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-11-29

Link To Source

Link To Answer
People are also looking for solutions of the problem: the process class relies on proc_open, which is not available on your php installation.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.


About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/



Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Formocr ошибка елочка
  • Formik onsubmit error
  • Formik error message
  • Formik error focus
  • Formhack сервер недоступен как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии