0

I am trying to copy one sheet of an .xlsx using phpspreadsheet with the following code:

$spreadsheet1 = \PhpOffice\PhpSpreadsheet\IOFactory::load("files/697D.xlsx");
$clonedWorksheet = clone $spreadsheet1->getSheetByName('Sheet');
$clonedWorksheet->setTitle('Test');
$spreadsheet->addSheet($clonedWorksheet);

But when I execute the code I get this error:

Fatal error: Uncaught Error: Call to a member function getCell() on null in C:\xampp\htdocs\OfferConfigurator\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Calculation\Calculation.php:2785 Stack trace: #0 C:\xampp\htdocs\OfferConfigurator\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Cell\Cell.php(262): PhpOffice\PhpSpreadsheet\Calculation\Calculation->calculateCellValue(Object(PhpOffice\PhpSpreadsheet\Cell\Cell), true) #1 C:\xampp\htdocs\OfferConfigurator\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx\Worksheet.php(1077): PhpOffice\PhpSpreadsheet\Cell\Cell->getCalculatedValue() #2 C:\xampp\htdocs\OfferConfigurator\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx\Worksheet.php(1027): PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet->writeCell(Object(PhpOffice\PhpSpreadsheet\Shared\XMLWriter), Object(PhpOffice\PhpSpreadsheet\Worksheet\Worksheet), 'J1', Array) #3 C:\xampp\htdocs\OfferConfigurator\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx\Worksheet.php(76): PhpOffice in C:\xampp\htdocs\OfferConfigurator\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Calculation\Calculation.php on line 2785

EDIT: I´m not an expert in phpspreadsheet, but I realized that maybe with clone it isn´t possible to copy formulas. Can that be the problem?

d1649356
  • 91
  • 1
  • 9
  • if you clone in same file, should use `$spreadsheet1` in `$spreadsheet->addSheet($clonedWorksheet);`. – Premlatha Feb 04 '20 at 01:22
  • @Premlatha That´s not the problem, $spreadsheet is defined in the code, but I haven´t written all the code in the question – d1649356 Feb 04 '20 at 11:02
  • Ok,try `$spreadsheet->addExternalSheet($clonedWorksheet);`. – Premlatha Feb 05 '20 at 01:21
  • @Premlatha I get the same error using $spreadsheet->addExternalSheet($clonedWorksheet); – d1649356 Feb 05 '20 at 07:34
  • @Premlatha Thank you for your help, finally I resolve the error. The problem was on the writer, that when it tried to write and calculate the formulas I get that error. I solve with this instruction: $writer->setPreCalculateFormulas(false); – d1649356 Feb 05 '20 at 12:01
  • Glad that you solve it. By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets.So, we can disable formula pre-calculation by `$writer->setPreCalculateFormulas(false);`before save it. – Premlatha Feb 06 '20 at 01:07

0 Answers0